<<
クラスで使用できるように、クラスの -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"
その演算子のオーバーロードについて話す必要はありません。どうすればこれを修正できますか?