为什么友元功能无法访问该类的私有成员

时间:2013-11-21 07:47:59

标签: c++ templates friend

执行此程序时,我遇到编译错误:

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&amp;运算符&lt;&lt;(std :: ostream&amp;,const currency&amp;)没有给出任何错误。我想知道程序中有什么问题吗?

另外,虽然我在课堂上给出了定义,但这是错误:

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

3 个答案:

答案 0 :(得分:3)

您的operator>>定义中的签名错误,这意味着您要声明并定义其他运算符。您需要从const声明中删除friend istream& operator,以便将其作为friend运算符的定义:

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

模糊的重载也是出于同样的原因。你有两个匹配的功能。上面提到的解决方案可以解决这两个问题。

答案 1 :(得分:2)

operator>>的签名与声明为该类的朋友的签名不匹配:

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

答案 2 :(得分:0)

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

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

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