[英]warning assignment operator class reference
i have this code: 我有此代码:
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;
};
befor i define assignment operator i get warning "assignment operator could not be generated". 在我定义赋值运算符之前,我得到警告“无法生成赋值运算符”。 i want assignment between object this class do nothing, its just class print in for_each algorithm. 我希望对象之间的分配该类不执行任何操作,而只是在for_each算法中打印该类。
i try write : 我尝试写:
ABC& operator=(const ABC& other){
return *this;
}
but still get warning the other not use. 但仍然得到警告,其他人不使用。 how can i define assignment operator do nothing. 我怎么能定义赋值运算符什么也不做。 (no Use the #pragma warning statement to suppress the warning). (否,使用#pragma warning语句禁止显示警告)。
thanks! 谢谢!
Few problems in your code... 您的代码很少有问题...
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;
};
Additionally, as operator()
defines course
as const Stud*
the print
method in Stud
class should be defined as const
as well. 另外,由于operator()
将course
定义为const Stud*
, Stud
类中的print
方法也应定义为const
。
other than that, the code compiles perfercly. 除此之外,代码可以完美地进行编译。
To get rid of the warning about an unused argument, just don't name it: 要摆脱有关未使用参数的警告,只需不命名即可:
ABC& operator=(const ABC&){
return *this;
}
The reason that the compiler can't generate an assignment operator for your class is that it has a reference variable, and these can only be initialised, never re-assigned. 编译器无法为您的类生成赋值运算符的原因是它具有一个引用变量,并且这些变量只能被初始化,而不能被重新赋值。
If you don't need an assignment operator, but only added one to make the compiler happy, you can declare it private
and then not provide an implementation. 如果不需要赋值运算符,而只添加了一个使运算符满意的运算符,则可以将其声明为private
,然后不提供实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.