C++ c+中的-运算符重载+;
虽然我没有使用赋值运算符,但为什么下面的代码会更改C++ c+中的-运算符重载+;,c++,operator-overloading,C++,Operator Overloading,虽然我没有使用赋值运算符,但为什么下面的代码会更改D1的值 #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance()
D1
的值
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main() {
Distance D1(1, 10), D2(-5, 11);
-D1; // apply negation
D1.displayDistance(); // display D1
-D2; // apply negation
D2.displayDistance(); // display D2
return 0;
}
#包括
使用名称空间std;
班距{
私人:
int英尺;//0到无穷大
int英寸;//0到12
公众:
//必需的构造函数
距离(){
英尺=0;
英寸=0;
}
距离(整数f,整数i){
英尺=f;
英寸=i;
}
//显示距离的方法
void显示距离(){
cout如果你不想让一个特定的函数改变你的类变量,你必须在它声明之后立即使用const
word。所以当你在这个函数中使用赋值语句时,编译器会向你抛出一个错误。
以下行用于更改当前正在处理的对象:
feet = -feet;
inches = -inches;
使用const
时,以下函数将引发编译器时间异常:
Distance operator- () const {
feet = -feet; // Compiler exception..
inches = -inches; // Compiler exception..
return Distance(-feet, -inches);
}
正如我所理解的,以下代码可以执行您想要的操作:
Distance operator- () const {
return Distance(-feet, -inches);
}
“虽然我没有使用赋值运算符?”您在运算符-
中使用了两次英尺=-feet;
和英寸=-inches;
@πάνταῥεῖ 我不确定它是否重复。问题不是问如何重写运算符-
。而是问为什么代码的行为如此。@Françoise可以随意重新打开。@Michelle如果是成员函数(包括运算符)不是为了修改它的实例,make是常量
,因此编译器可以发出此类错误的信号。例如距离运算符-()常量
。dupe已经死了,但仍然是一个高度推荐的读取和书签。其中包含许多智慧。