Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 重载运算符-警告:语句无效[-Wunused值]_C++ - Fatal编程技术网

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;
}