1

<<クラスで使用できるように、クラスの -operatorをオーバーロードしようとしstd::coutています。これを行うためにオンラインで見つけたコードをいくつかコピーしましたが、動作させることができません。
次のようなエラーが表示されます。

error C2662: 'nspace::ElementCopy::name' : cannot convert 'this' pointer 
from 'const nspace::ElementCopy' to 'nspace::ElementCopy &'

エラーは<<-operator の実装にあります: (コードのコメントを参照)


ここに私のヘッダーファイルElementCopy.hがあります:

#pragma once
#include <string>
#include <iostream>

namespace nspace
{
    class ElementCopy
    {
        public:
            std::string name();
    };

    std::ostream& operator<< (std::ostream& stream, const ElementCopy& arg)
    {
        stream << arg.name(); //compiler error at this line
        return stream;
    }
}

そして、これが私の短いコード ファイルElementCopy.cppです。

#include "ElementCopy.h"

namespace nspace
{
    std::string ElementCopy::name()
    {
        return "string";
    }
}

このエラーがわかりません。なぜ私はそれを手に入れているのですか?"this"その演算子のオーバーロードについて話す必要はありません。どうすればこれを修正できますか?

4

4 に答える 4

4

name()メソッドを作成したいconst

class ElementCopy
{
    public:
        std::string name() const;
};

constこのようにして、あなたの参照でそれを呼び出すことができますoperator<<

于 2013-09-04T19:32:22.820 に答える
3

引数argconst参照ですが、ElementCopy::nameメソッドは非定数です。を追加するだけconstです:

        std::string name() const;
于 2013-09-04T19:32:32.990 に答える
1

左の引数はオブジェクトではなくストリームであるため、演算子は自由な関数である必要があります。通常、クラス内でフレンドにすることでこれを実現します。

friend std::ostream& operator<< (std::ostream& stream, const ElementCopy& arg)
{
    return stream << arg.name();
}

は public メンバー関数であるためname()、この全体をクラス定義の外で宣言することもできます。通常、friendリレーションシップは、ストリーム オペレーターのためだけにゲッターを必要とせずにプライベート メンバーに便利にアクセスするために使用されます。

于 2013-09-04T19:31:53.177 に答える