[英]Using overloaded + operator in derived class
我正在練習從派生類(在我的例子中是飛機)中使用重載賦值運算符,它工作得很好。 我遇到的問題是 + 運算符重載。 它應該只是對兩個 Airplane 對象的 engine_power 和座位求和,然后在求和飛行速度(粗線)之后。 And it really does go to the Base class overloaded + operator function when called from derived class (Vehicle::operator +(rhs);), but then Vehicle variable temp sums everything as it should do, but for some reason calls destructor right after並且我的派生對象的基本 class 屬性保持為 0。期待任何建議或建議
#include <iostream>
using namespace std;
class Vehicle {
protected:
int engine_power;
int seats;
public:
Vehicle(int engine_power, int seats)
: engine_power{engine_power},seats{seats}{
cout << "Vehicle constructor" << endl;
}
Vehicle &operator=(const Vehicle &rhs){
cout << "Vehicle assignment" << endl;
if (this==&rhs)
return *this;
else{
engine_power=rhs.engine_power;
seats=rhs.seats;
return *this;
}
}
Vehicle operator+(const Vehicle &rhs){
Vehicle temp{0,0};
temp.engine_power=engine_power+rhs.engine_power;
temp.seats=seats+rhs.seats;
return temp;
}
~Vehicle() {
cout << "Vehicle destructor" << endl;
}
};
class Airplane : public Vehicle {
private:
int flying_speed;
public:
Airplane(int a, int b, int flying_speed)
: Vehicle{a,b}, flying_speed{flying_speed}{
cout << "Airplane constructor" << endl;
}
Airplane &operator= (const Airplane &rhs){
cout << "Airplane assignment" << endl;
if (this!=&rhs){
Vehicle::operator =(rhs);
flying_speed=rhs.flying_speed;
return *this;
} else
return *this;
}
Airplane operator+ (const Airplane &rhs) {
Airplane temp{0,0,0};
**Vehicle::operator +(rhs);**
**temp.flying_speed=flying_speed+rhs.flying_speed;**
return temp;
}
~Airplane() {
cout << "Airplane destructor" << endl;
}
};
int main(){
Airplane a1 {10,20,30};
Airplane a2 {10,22,33};
Airplane a3 = a1+a2;
return 0;
}
正如評論中所指出的,當在派生的 class 中調用時,您不會存儲基礎 class Vehicle::operator+()
的結果。 這是固定代碼:
#include <iostream>
using namespace std;
class Vehicle {
protected:
int engine_power;
int seats;
public:
Vehicle(int engine_power, int seats)
: engine_power{engine_power},seats{seats}{
//cout << "Vehicle constructor" << endl;
}
Vehicle operator+(const Vehicle &rhs){
Vehicle temp{0,0};
temp.engine_power=engine_power+rhs.engine_power;
temp.seats=seats+rhs.seats;
return temp;
}
};
class Airplane : public Vehicle {
private:
int flying_speed;
public:
Airplane(int a, int b, int flying_speed)
: Vehicle{a,b}, flying_speed{flying_speed}{
//cout << "Airplane constructor" << endl;
}
Airplane operator+ (const Airplane &rhs) {
Airplane temp{0,0,0};
static_cast<Vehicle&>(temp) = Vehicle::operator +(rhs);
temp.flying_speed=flying_speed+rhs.flying_speed;
return temp;
}
void print() const {
cout << " power " << engine_power
<< " seats " << seats
<< " speed " << flying_speed
<< std::endl;
}
};
int main(){
Airplane a1 {10,20,30};
Airplane a2 {10,22,33};
Airplane a3 = a1+a2;
a3.print();
return 0;
}
Output: power 20 seats 42 speed 63
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.