在编写继承类时,发现运行基类函数时调用的是基类中的私有变量,而不是想用的继承类中的同名变量
你这代码里哪里有继承
继承类中不要再弄同名变量,如果再弄同名变量不就失去继承的意义了吗
代码不全?
你的基类中没有对name的get和set函数。
如下:
#include <iostream>
#include <string>
using namespace std;
class Shape
{
public:
Shape(void){}
string getColor(){return Color;}
void setColor(string color){Color = color;}
string getName(){return name;}
void setName(string nn){name = nn;}
string toString()
{
string temp = name;
if(Color == "") temp += " (#)";
else temp += Color;
return temp;
}
//...
private:
string Color;
string name;
};
class Circle :public Shape
{
public:
Circle(){}
//
};
int main()
{
Circle cc;
//因为Color是private成员,所以必须使用函数才能使用,如果Color是public,可以在Circle类中直接使用
cc.setColor("red"); //使用继承的函数设置color
cout << cc.getColor() << endl; //使用继承的getColor函数获取成员变量
cc.setName("test");
cout << cc.getName() << endl;
cout << cc.toString() << endl;
return 0;
}
private改成protected