如果我有一个带有重载赋值运算符的类,如下所示:
template<typename T> class Foo {
private:
T var;
public:
T operator=(T v){var = v;};
};
它有效,但是如果我想在类之外定义运算符,它告诉我T
不是一个类型(它是正确的)。我怎样才能绕过这个并在课堂外定义它?
答案 0 :(得分:0)
您可以按如下方式在类之外定义它:
template<typename T>
Foo<T>& Foo<T>::operator=(T v)
// Note the Foo& that was added (it needs to be added to the declaration too)
// This is the idiomatic way to implement the assignment operator
{
var = v;
return *this;
}