10

フレンド関数は、クラスのプライベート メンバーにアクセスできるはずですよね? それで、私はここで何を間違えましたか?.h ファイルに operator<< を含めました。このクラスと仲良くするつもりです。

#include <iostream>

using namespace std;
class fun
{
private:
    int a;
    int b;
    int c;


public:
    fun(int a, int b);
    void my_swap();
    int a_func();
    void print();

    friend ostream& operator<<(ostream& out, const fun& fun);
};

ostream& operator<<(ostream& out, fun& fun)
{
    out << "a= " << fun.a << ", b= " << fun.b << std::endl;

    return out;
}
4

3 に答える 3

13

ここに...

ostream& operator<<(ostream& out, fun& fun)
{
    out << "a= " << fun.a << ", b= " << fun.b << std::endl;

    return out;
}

あなたが必要

ostream& operator<<(ostream& out, const fun& fun)
{
    out << "a= " << fun.a << ", b= " << fun.b << std::endl;

    return out;
}

(私はこれに何度も悩まされてきました。演算子オーバーロードの定義は宣言と完全には一致しないため、別の関数であると考えられます。)

于 2010-07-17T10:24:16.420 に答える
6

署名が一致しません。あなたの非メンバー関数は楽しみと楽しみを取り、で宣言された友人はconstの楽しみと楽しみを取ります。

于 2010-07-17T10:24:29.663 に答える
0

クラス定義内にフレンド関数定義を記述することで、この種のエラーを回避できます。

class fun
{
    //...

    friend ostream& operator<<(ostream& out, const fun& f)
    {
        out << "a= " << f.a << ", b= " << f.b << std::endl;
        return out;
    }
};

欠点は、すべての呼び出しoperator<<がインライン化されるため、コードが肥大化する可能性があることです。

fun(また、その名前はすでに型を示しているため、パラメーターを呼び出すことができないことに注意してください。)

于 2010-07-17T10:42:29.517 に答える