C++ 重载运算符-警告:语句无效[-Wunused值]
我有以下编码的操作员过载:C++ 重载运算符-警告:语句无效[-Wunused值],c++,C++,我有以下编码的操作员过载: Clase &operator*(Clase const & n){ coeficiente_*n.coeficiente_; grado_*n.grado_; return *this; } 编译时,我收到以下警告: clase.hpp:62:18: warning: statement has no effect [-Wunused-value] coeficiente_*n.coeficiente_;
Clase &operator*(Clase const & n){
coeficiente_*n.coeficiente_;
grado_*n.grado_;
return *this;
}
编译时,我收到以下警告:
clase.hpp:62:18: warning: statement has no effect [-Wunused-value]
coeficiente_*n.coeficiente_;
^
警告是什么意思?我该怎么解决呢?你的陈述
coeficiente_*n.coeficiente_;
grado_*n.grado_;
没有效果。它们和写作一样
5;
24;
"123";
也许你想做这样的任务
coeficiente_ *= n.coeficiente_
grado_ *= n.grado_;
?编译器警告您,
coeficiente\u*n.coeficiente\u
和grado\u*n.grado\u
无效。为了让它们产生效果,应该将结果分配给某个对象。为了这个例子,我将假设一个int
类型
int c = coeficiente_*n.coeficiente_;
int g = grado_*n.grado_;
操作员的形式看起来也不正确,因为OP和
Clase a, b;
// initialise as required
c = a * b;
乘法将修改a
,结果c
将与a
相同;因为提供的运算符看起来是一个成员方法,结果通过引用返回(到this
)。这可能不是操作员的意图*
有,作为非成员函数提供操作符*
(可能具有朋友访问权限),或从成员方法返回新对象
Clase operator*(Clase const & n) /*const*/
{
Clase result; // assumption is their is a default constructor for this example
result.coeficiente_ = coeficiente_ * n.coeficiente_;
result.grado_ = grado_ * n.grado_;
return result;
}
成员方法也可以根据需要/需要标记为const
非成员实现可能如下所示(我保留了大部分实现进行比较):
这个警告有什么不清楚的地方?你需要把乘法的结果存储在某个地方,否则就没有效果了。除了两个数字相乘之外,你希望两个数字相乘还能做什么?(盘车操作员过载)
Clase operator*(Clase const & l, Clase const & r)
{
Clase result;
result.coeficiente_ = l.coeficiente_ * r.coeficiente_;
result.grado_ = l.grado_ * r.grado_;
return result;
}