访问派生类 C++ 中的受保护变量

access protected variable in derived class c++

本文关键字:受保护 变量 C++ 派生 访问      更新时间:2023-10-16

我有一个母类和一个派生的子类。我正在尝试访问派生类中的受保护变量"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;
}

你在面向对象编程中没有一个明确的概念。当您创建两个对象时,它们彼此完全不同。在被迫之前,它们不会相互交流。所以

  • myMummyDaughter 是单独的对象,它们不共享其变量的值。
  • 最后两个输出基本上是垃圾值。您尚未初始化我女儿的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;
    }

您将获得所需的输出!!

这里有几点错误:

  1. myDaughtermyMum不同的对象。你暗示他们之间有某种关系,但没有。

  2. 代码具有未定义的行为,因为Daughter构造函数在加法运算中使用未初始化的成员变量familystuff

  3. 您应该像这样初始化数据成员:

    Mother::Mother() : motherstuff(0), familystuff(0), everyonesstuff(0) {}

    Daughter::Daugher() : a(familystuff + 1) {}