C++ 在运算符重载中使用参数调用类

C++ 在运算符重载中使用参数调用类,c++,polymorphism,operator-overloading,C++,Polymorphism,Operator Overloading,考虑以下代码: #include <iostream> using namespace std; class Distance{ int feet,inches; public: Distance (int feet,int inches){ this->feet=feet; this->inches=inches; } Distance operator-(){ this->f

考虑以下代码:

#include <iostream>
using namespace std;
class Distance{
    int feet,inches;
    public:
    Distance (int feet,int inches){
        this->feet=feet;
        this->inches=inches;
    }
    Distance operator-(){
        this->feet=-(this->feet);
        this->inches=-(this->inches);
        return Distance(feet,inches);
        // return *this; 
    }
    void show(){
        cout << "Value of feet is " << this->feet <<endl;
        cout << "Value of inches is " << this->inches << endl;
    }
};
int main(){
    Distance d1(90,80);
    -d1;
    d1.show();
    return 0;
}
在这里,我们如何在不创建类距离的对象的情况下调用构造函数,我们也可以调用类的构造函数吗

在我看来,这句话应该是这样的:

Distance d1;
return d1(feet,inches);

如果不创建类距离的对象,我们如何调用构造函数?我们是否也可以调用类的构造函数?
此行正在创建一个对象。您的操作员正在做一些不应该做的事情:修改自己的对象!您需要先创建一个新对象,然后在该对象上设置新值。我建议您将整个函数设置为
const
,如
Distance operator-()const
@tkausl您能告诉我正在创建的新对象的名称吗?@tkausl据我所知,创建对象的语法是class name后跟object name
Distance(英尺,英寸)
创建一个临时对象,由编译器自己处理。在将其分配给变量之前,它没有“名称”。如
some_distance=距离(英尺,英寸)
Distance d1;
return d1(feet,inches);