我想将Soldier类的对象John转换成Sergeant类(代表升官了),名字不变,但我发现我的代码实现不了,原因是重定义了。我想知道有没有什么办法可以不改我的对象名字(John)而转换它的类类型
#include<iostream>
using namespace std;
class Soldier {
friend class Sergeant;
public:
Soldier(long long a, string b, string c, int d) :id(a), name(b), sex(c), year(d) {}
private:
long long id;
string name;
string sex;
int year;
};
class Sergeant {
public:
Sergeant() {}
Sergeant(long long a, string b, string c) :id(a), name(b), sex(c) {}
Sergeant(Soldier& sd) {
id = sd.id;
name = sd.name;
sex = sd.sex;
}
void Display() {
cout << "name: " << name << endl
<< "id: " << id << endl
<< "sex: " << sex << endl;
}
private:
long long id;
string name;
string sex;
};
int main() {
Soldier John(20200001, "John", "male", 2);
Sergeant John = John; //这行和下一行都是错误的
John.Display();
return 0;
}
有大佬回答的话我会非常感激的 ||o(*°▽°*)o|Ю