c++ - 多重继承需要访问私有(private)变量

标签 c++ inheritance virtual

我不知道如何访问私有(private)变量多重继承。

在这段代码中我创建了person

class person {
    char name[20]; char lname[20];
public:
    person() {}
    person(char*n, char*ln);
    virtual void print(ostream&o);
};
person::person(char*n, char*ln)
{
    strcpy_s(name, 20, n);
    strcpy_s(lname, 20, ln);
}

void person::print(ostream&o)
{
    o << "name: " << name << "  " << "last name: " << lname << endl;
}
ostream& operator<<(ostream&o, person&p)
{
    p.print(o);
    return o;
}

通过继承我创建了studentteacher

class student : public virtual person
{friend class ststudent;

    long str;
public:

    student(char*n, char*ln, long s);
    void print(ostream&o);
};

student::student(char*n, char*ln, long s) :person(n, ln), str(s) {}

void student::print(ostream&o)
{
    person::print(o);
    o << "st_num :  " << str << endl;
}




class teacher : public virtual person
{
    long salary;

public:

    teacher(char*n, char*ln, long s);
    virtual void print(ostream&o);
};

teacher::teacher(char*n, char*ln, long sal) :person(n, ln), salary(sal) {}

void teacher::print(ostream&o)
{
    person::print(o);
    o << "salary :  " << salary << endl;
}

在上一个类中,我使用多重继承来创建助教类,但我不知道如何打印 strsalary

class stteacher :public teacher, public student
{

public:
    stteacher(char*n, char*ln, long st, long sa)
        :student(0, 0, st), teacher(0, 0, sa), person(n, ln) {}
    virtual void print(ostream&o);
};

void stteacher::print(ostream& o)
{
    person::print(o);
    o << str << salary;

}

我不知道怎么办。我可以在 stteacher 类中创建两个变量或将 strsalary 从私有(private)变量更改为公共(public)变量,但我认为我应该使用多重继承来做到这一点。 请帮助我。

最佳答案

类中的私有(private)数据不能被任何非成员、非友元代码访问。时期。是否使用继承(或不使用)无关紧要。

因此,不同类访问该数据的唯一方法是:

  • 提供访问器函数,以便调用者可以获取数据。 (如果是公共(public)的,任何人都可以调用它,但如果它是 protected 函数,则只有派生类可以访问它。)

  • 或者,让需要访问的类(class)成为类(class)的 friend 。然而,友元是 C++ 程序员通常不鼓励的,所以只有在真正的最后手段时才这样做。

  • 将对数据的访问更改为公开。 (非常气馁,因为这完全破坏了封装。)

关于c++ - 多重继承需要访问私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153745/

相关文章:

c++ - 在 C++ 流中包装 C 风格的文件

c++ - 异或两个双变量

c++ - 使用前重置成员变量

java - Java 中的字段继承

c++ - 将 Open GL ES 与 iOS 混合使用

javascript - 使用单个全局命名空间,如何从工具的方法访问命名空间的属性/方法?

c# - USB 闪存驱动器模拟(如 cd/dvd rom 虚拟驱动器)-是否可能

mysql - 从文本列创建时间戳虚拟列

c# - 检测游戏是否在安卓模拟器中运行

c++ - 函数模板和私有(private)继承