访问派生类 C++ 中的受保护变量
access protected variable in derived class c++
我有一个母类和一个派生的子类。我正在尝试访问派生类中的受保护变量"familystuff"。我尝试访问它的两种方式都不起作用。当我编译并运行它时,我得到以下输出:
5 3 1
1
家庭 32768
FOO 32767
class Mother
{
private:
int motherstuff;
protected:
int familystuff;
public:
int everyonesstuff;
void SetStuff(int a, int b, int c){
motherstuff = a;
familystuff = b;
everyonesstuff = c;
}
void Show(){
cout << motherstuff << " " << familystuff << " " <<everyonesstuff << endl;
}
};
class Daughter : public Mother
{
public:
Daughter()
{
a = familystuff + 1;
}
void Show(){
cout << "Familie " << a << endl;
}
int foo() { return familystuff;}
private:
int a;
};
int main(){
Mother myMum;
myMum.SetStuff(5,3,1);
myMum.Show();
cout << myMum.everyonesstuff << endl;
Daughter myDaughter;
myDaughter.Show();
cout << "FOO " << myDaughter.foo() << endl;
}
你在面向对象编程中没有一个明确的概念。当您创建两个对象时,它们彼此完全不同。在被迫之前,它们不会相互交流。所以
-
myMum
和myDaughter
是单独的对象,它们不共享其变量的值。 - 最后两个输出基本上是垃圾值。您尚未初始化我女儿的
familystuff
因此,如果要从派生类访问受保护的成员,则需要编写以下内容:
int main()
{
Daughter myDaughter(5,3,1);
myDaughter.Show();
cout << "FOO " << myDaughter.foo() << endl;
}
将女儿的构造函数更改为以下内容:
Daughter(int x,int y,int z)
{
SetStuff(x,y,z);
a = familystuff + 1;
}
您将获得所需的输出!!
这里有几点错误:
-
myDaughter
和myMum
是不同的对象。你暗示他们之间有某种关系,但没有。 -
代码具有未定义的行为,因为
Daughter
构造函数在加法运算中使用未初始化的成员变量familystuff
。 -
您应该像这样初始化数据成员:
Mother::Mother() : motherstuff(0), familystuff(0), everyonesstuff(0) {}
Daughter::Daugher() : a(familystuff + 1) {}
相关文章:
- 如何从其他结构访问受保护的结构变量
- 从模板化父类中的派生内部类访问受保护的成员变量
- C++中的受保护变量
- 如何影响派生类中受保护的基变量
- C++,如何创建线程限制/受保护的变量和函数
- 类的静态成员变量(受保护)的作用域
- 无法在受保护的类中显示变量
- 虚函数在受保护变量上触发编译错误
- 为什么我无法访问作为参数传递到函数中的基类的受保护成员变量?
- 访问受保护的变量 - 继承和子类的复杂情况
- 继承受保护的函数和公共变量C++时发生多重继承编译错误
- 为什么可以从派生实例访问基类中的受保护变量
- 继承中使用的受保护变量
- 有没有办法从类外部声明一个受保护C++变量?
- 访问派生类 C++ 中的受保护变量
- 受保护变量的命名和标准
- 重写派生类中的受保护变量
- 告诉子类对超类的受保护变量执行某些操作是否是一种好的做法(也许是一些已知的设计模式?)?
- 从类C访问类a中的受保护变量,其中C是B的子类,B是a的子类
- 如何访问子节点的受保护变量