重载<

问题描述 投票:-1回答:2

我正在尝试从类operator<<中重载second。问题是我尝试访问的某些数据在类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; 
c++ inheritance operator-overloading friend
2个回答
1
投票

写作时

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

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.