この問題はテンプレート化されたクラスで発生しました。ここ は、私が使用していたより一般的なソリューションです:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// Friend means operator<< can use private variables
// It needs to be declared as a template, but T is taken
template <class U>
friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}
// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
obj.toString(os);
return os;
}
今:CPPに隠れされようとしている場合 *私のtoString()関数はinlineにできません。 *ヘッダーにコードが付いているので、取り除くことができませんでした。 *演算子はtoString()メソッドを呼び出しますが、インライン化されていません。
オペレータの本文< <は、フレンド節またはクラス外で宣言できます。どちらのオプションも醜いです。
たぶん私は誤解や不足している何かを、ちょうどオペレータテンプレートは、GCCにリンクしません、前方宣言しています:(
これはあまりにも動作します。
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// For some reason this requires using T, and not U as above
friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
{
obj.toString(os);
return os;
}
}
私はあなたにもできると思います< <を実装するためにテンプレート化されていない親クラスを使用し、virtual toString()メソッドを使用する場合は、ヘッダーの宣言を強制的にテンプレート化する問題を避けてください。
さらに、彼はfriend関数として宣言し、私のようにmber機能。 – asaelr