gpt4 book ai didi

C++ - 将派生类的对象复制到基类的对象中

转载 作者:行者123 更新时间:2023-11-28 00:42:22 27 4
gpt4 key购买 nike

由于重载运算符=的限制,我们不能将派生对象复制到基类的对象中。那么,为什么我们可以将派生对象的地址复制到基类的指针中呢?不应该相反吗,因为派生对象比基类对象大。事实上,当我尝试它时,我得到了一个错误,提示 不允许将基对象转换为派生对象。你能告诉我为什么吗?我无法在互联网上找到任何相关信息。代码如下:-

#include<string>
#include<vector>
#include<iostream>
using namespace std;
class employee
{
protected:
string name;
double pay;
public:
employee(string ename,double payRate)
{
name = ename;
pay = payRate;
}
virtual double GrossPay(int days)
{
return pay*days;
}
virtual string getName()
{
return name;
}
};
class manager:public employee
{
private:
bool salaried;
public:
manager(string ename,double payRate,bool isSalaried):employee(ename,payRate)
{
salaried = isSalaried;
}
virtual double GrossPay(int days)
{
if(salaried)
return pay;
else
return pay*days;
}
};
int main(void)
{
employee* emp2;
employee emp3("Bill",350);
manager mgr3("Alice",200,true);
emp2 = &emp3;
cout<<emp2->getName()<<" earns "<<emp2->GrossPay(40)<<endl;
emp2 = &mgr3;
cout<<emp2->getName()<<" earns "<<emp2->GrossPay(40)<<endl; // The code works till here
//The problematic part starts from here:-
manager* mgr6;
employee emp5("NewBill",300);
mgr6 = &emp5;
cout<<mgr6->getName()<<" earns "<<mgr6->GrossPay(40)<<endl;
return 0;
}

注意:我显示的错误是编译器实际显示的错误。

最佳答案

manager* mgr6;                                          
employee emp5("NewBill",300);
mgr6 = &emp5;

在您的示例中,manager 类派生自 employee 类。所以,emp5 是一个基类对象。它不知道派生类成员。

mgr6manager * 类型,它试图指向 emp5。如前所述,emp5 没有用于分配操作的派生类子对象。

但是,这是可行的。

employee* emp2;
manager mgr3("Alice",200,true);
emp2 = &mgr3;

因为,mgr3 同时具有派生类和基类子对象。

编辑:在最后一行将 emp3 更正为 mgr3

关于C++ - 将派生类的对象复制到基类的对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153184/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com