【问题标题】:Overloading << Cannot Access Inherited Private Data重载 << 无法访问继承的私有数据
【发布时间】:2020-02-07 06:51:00
【问题描述】:

我正在尝试从 second 类中重载 operator&lt;&lt;。问题是我试图访问的一些数据在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


【解决方案1】:

正如其他人所说,第二类无法访问第一类的私有成员。您可以尝试在第一堂课中编写一些 set 和 get 方法。 get 方法将返回值(我假设您正在寻找)。您可以在第二类中调用此函数。不确定这是否超出了您正在寻找的东西。可能只想在第一个类中进行重载

【讨论】:

  • 谢谢,我认为这是我必须采用的真正解决方案!
【解决方案2】:

当你写作时

friend ostream &operator << (ostream &output, second &dS);

您允许具有该签名的某些外部函数访问您的second 类可以访问的任何内部属性/成员。这意味着operator&lt;&lt; 将有权访问属性f,即使它是私有的。但是,您的 second 类无权访问基类中的私有数据。因此,它不能授予对 friend 函数的访问权限。

【讨论】:

    猜你喜欢
    • 2018-12-12
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2011-12-22
    • 2013-09-09
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    相关资源
    最近更新 更多