我不知道如何访问私有(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;
}
通过继承我创建了student
和teacher
类
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;
}
在上一个类中,我使用多重继承来创建助教类,但我不知道如何打印 str
和 salary
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
类中创建两个变量或将 str
和 salary
从私有(private)变量更改为公共(public)变量,但我认为我应该使用多重继承来做到这一点。
请帮助我。
最佳答案
类中的私有(private)数据不能被任何非成员、非友元代码访问。时期。是否使用继承(或不使用)无关紧要。
因此,不同类访问该数据的唯一方法是:
提供访问器函数,以便调用者可以获取数据。 (如果是公共(public)的,任何人都可以调用它,但如果它是 protected 函数,则只有派生类可以访问它。)
或者,让需要访问的类(class)成为类(class)的 friend 。然而,友元是 C++ 程序员通常不鼓励的,所以只有在真正的最后手段时才这样做。
将对数据的访问更改为公开。 (非常气馁,因为这完全破坏了封装。)
关于c++ - 多重继承需要访问私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153745/