[英]warning assignment operator class reference
我有此代码:
class ABC{
public:
ABC(std::ostream& os) : _os(os) {}
void operator() (const Stud* course) {
Stud->print(_os);
}
ABC& operator=(const ABC& other); //Declaration of operator=
private:
std::ostream& _os;
};
在我定义赋值运算符之前,我得到警告“无法生成赋值运算符”。 我希望对象之间的分配该类不执行任何操作,而只是在for_each算法中打印该类。
我尝试写:
ABC& operator=(const ABC& other){
return *this;
}
但仍然得到警告,其他人不使用。 我怎么能定义赋值运算符什么也不做。 (否,使用#pragma warning语句禁止显示警告)。
谢谢!
您的代码很少有问题...
class ABC
{
public:
ABC(std::ostream& os) : _os(os) {}
void operator() (const Stud* course)
{
//Stud->print(_os); // you can't use Stud here - this is wrong
course->print(_os);
}
ABC& operator=(const ABC& other); //Declaration of operator=
private:
std::ostream& _os;
};
另外,由于operator()
将course
定义为const Stud*
, Stud
类中的print
方法也应定义为const
。
除此之外,代码可以完美地进行编译。
要摆脱有关未使用参数的警告,只需不命名即可:
ABC& operator=(const ABC&){
return *this;
}
编译器无法为您的类生成赋值运算符的原因是它具有一个引用变量,并且这些变量只能被初始化,而不能被重新赋值。
如果不需要赋值运算符,而只添加了一个使运算符满意的运算符,则可以将其声明为private
,然后不提供实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.