警告赋值操作符类引用
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算法中打印类。
i try write:ABC& operator=(const ABC& other){
return *this;
}
,但仍然得到警告,其他不使用。我如何定义赋值操作符什么都不做。(不使用#pragma warning语句来抑制警告)。
谢谢!
要摆脱关于未使用参数的警告,只需不命名它:
ABC& operator=(const ABC&){
return *this;
}
编译器不能为你的类生成赋值操作符的原因是它有一个引用变量,而这些变量只能初始化,不能重新赋值。
如果你不需要赋值操作符,而只是为了让编译器满意而添加了一个赋值操作符,你可以声明它为private
,然后不提供实现。
你的代码中有几个问题…
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
。
相关文章:
- 使用变量参数列表为传递的引用赋值(VS2010中出错)
- 在 C++ 中通过引用返回 - 引用赋值与值赋值
- 为什么不能为非常量引用赋值
- c++ 取消引用赋值是按位赋值还是按位赋值或"smart"赋值?
- 类成员作为对另一个的引用:赋值运算符中的崩溃
- c++中的重载赋值操作符
- c++类继承和赋值操作符
- 带引用类成员的赋值操作符
- 复制构造函数,赋值操作符重载
- c++派生类赋值操作符
- 通过调用Move赋值操作符实现Move构造函数
- 带有映射的赋值操作符
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 为具有引用成员变量的类创建赋值操作符
- 警告赋值操作符类引用
- 声明对对象的引用和赋值操作符
- 如何处理赋值操作符和复制构造函数中的引用数据成员
- 如何编写一个拷贝赋值操作符来处理引用