【问题标题】:Why friend function is not able to access private members of the class为什么朋友功能无法访问班级的私人成员
【发布时间】:2013-11-21 07:47:58
【问题描述】:

在执行此程序时,我收到以下编译错误:

template.cpp: In function ‘std::istream& operator>>(std::istream&, currency&)’:
template.cpp:8: error: ‘int currency::doller’ is private
template.cpp:25: error: within this context
template.cpp:9: error: ‘int currency::cents’ is private
template.cpp:25: error: within this context

这是c++程序:

#include <iostream>
using namespace std;

class currency
{
    private: 
        int doller;
        int cents;

    public:
        currency():doller(0),cents(0) {}
        friend ostream& operator<< (ostream& stream, const currency& c );
        friend istream& operator>> (istream& in, const currency& c);

        /*friend istream& operator>> (istream& in, const currency& c)
        {
            in >> c.doller >> c.cents;
            return in;
        } */
};

istream& operator>> (istream& in, currency& c)
{
    in >> c.doller >> c.cents;
    return in;
} 

ostream& operator<< (ostream& stream, const currency& c )
{
    stream << "(" << c.doller << ", " << c.cents << ")";
    return stream;
}

template <class T>
void function(T data)
{
    cout << "i am in generalized template function: " << data << endl;
}

template<>
void function (int data)
{
    cout << "This is: specialized for int" << data << endl;
}

int main()
{
    currency c;
    cin >> c;
    function (c);
    function (3.14);
    function ('a');
    function (12);
    return 0;
}

同时 std::ostream& operator

另外,当我在类中给出定义时,这是错误:

template.cpp: In function ‘std::istream& operator>>(std::istream&, const currency&)’:
template.cpp:18: error: ambiguous overload for ‘operator>>’ in ‘in >> c->currency::doller’

【问题讨论】:

    标签: c++ templates friend


    【解决方案1】:

    您的operator&gt;&gt; 定义中有错误的签名,这意味着您声明和定义了不同的运算符。您需要从 friend istream&amp; operator 声明中删除 const 以使其成为 friend 运算符的定义:

    friend
    istream& operator>> (istream& in, currency& c)
    //                                
    

    模棱两可的重载也是出于同样的原因。您有两个匹配的功能。上面建议的修复方法可以解决这两个问题。

    【讨论】:

    • 根据其运营商货币的逻辑不应该是const,因为他在>> c.doller >> c.cents的这条语句中修改了它;所以最好更改朋友的签名(省略 const)
    • 感谢您的快速回复。
    【解决方案2】:

    operator&gt;&gt; 的签名与声明为类朋友的签名不匹配:

    istream& operator>> (istream& in, currency& c);        // outside class
    istream& operator>> (istream& in, const currency& c);  // friend class
    //                                ^^^^^
    

    【讨论】:

    • 谢谢,我的签名也不匹配。
    【解决方案3】:

    您需要删除方法声明中的 const 签名:

    friend istream& operator>> (istream& in, currency& c);
    

    定义的函数中没有const,因此它不是您声明为friend 的函数,因此无法访问private 成员。请注意,声明 currency 对象 const 也没有意义,因为您使用 instream 运算符对其进行更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      相关资源
      最近更新 更多