由于重载运算符的限制,我们不能将派生对象复制到基类的对象中=
。那么,为什么我们可以将派生对象的地址复制到基类的指针中呢?不应该反过来,因为派生对象的大小比基类对象大。事实上,当我尝试它时,我得到了一个错误,上面写着the conversion of a base object to the derived object is not allowed
. 你能告诉我为什么吗?我无法在互联网上找到任何相关信息。代码如下:-
#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;
}
注意:我显示的错误是编译器实际显示的简化。