【发布时间】:2020-02-07 06:51:00
【问题描述】:
我正在尝试从 second 类中重载 operator<<。问题是我试图访问的一些数据在first 类中是私有的。为什么我在使用好友功能时无法访问隐私数据?
我发现重载仅适用于非继承的私有数据。
class first
{
public:
student(string a, string b, float c, int d);
private:
string a;
string b;
float c;
int d;
int e;
static int count;
};
class second : public first
{
public:
second(string a, string b, float c, int d, string f);
friend ostream &operator << (ostream &output, second &dS);
friend istream &operator >> (istream &input, second &dS);
private:
string f;
};
// Separate File
ostream &operator <<(ostream& output, second& dS){
output << iS.a << endl;
output << iS.f << endl;
return output;
}
这是我得到的错误:
overload.cpp:27:18: error: 'a' is a private member of 'first'
output << dS.a << endl;
^
./example.hpp:51:9: note: declared private here
string a;
【问题讨论】:
-
它是因为 second 无权访问这些变量。如果您想在子类中访问它们,它们必须受到保护而不是私有
-
class second也无法访问这些变量。这就是private的工作原理。它们归class first私人所有。 -
你的朋友可以看到你的私处,但他们看不到你父母的私处。
标签: c++ inheritance operator-overloading friend