c++中的多态性和运算符重载混淆

Polymorphism and operator overloading confusion in c++

本文关键字:重载 运算符 多态性 c++      更新时间:2023-10-16

我不知道如何用我在上面定义的>>运算符读取ageMonth。我必须创建一个动态对象gos=new Baby,但当我这样做时,我不知道对象的名称,所以我不能将其传递给>>运算符。

class Human{
public:
    virtual void write();
};
class Baby:public Human{
int ageMonth;
public:
    friend istream& operator>>(istream& is,Human* ref);
    void write(){cout<<"Average mass of the baby: "<<(ageMonth+9)/2<<endl;
    }
};
istream& operator>>(istream& is,Human* ref){
is>>ref->ageMonth;  //This gives error
return is;
}

int main(){
char ch;
Insan* gos;
cout<<"Enter B for baby , C for children: "<<endl;
cin>>ch;
if(ch=='B'){
    gos=new Baby;
    cout<<"Enter the age of the baby as month "<<endl;
    cin>>gos; //gives error
    gos->write();

处理引用,而不是指针定义运算符

class Baby:public Human{
    // ...
    friend istream& operator>>(istream& is, Baby* ref);

这只是说,"有一些operator>>函数在其他地方定义,我允许对(指向)Baby对象的指针进行操作"。您仍然需要定义该函数。

然后,这在指针上就不起作用了。您需要一个现有对象进行操作,用您从输入中读取的内容设置其成员变量。这就是为什么operator>>需要是friend:它需要访问成员。

您的行Baby * gos;并没有创建要处理的对象,它只是创建了一个指针(不指向任何位置)。

因此,定义函数来操作引用,而不是指针。

friend istream& operator>>(istream & is, Baby & ref);

然后定义函数:

istream& operator>>(istream& is, Baby & ref)
{
    cin >> ref.ageMonth;
    // ...
}

然后你应该能够使用它:

Baby gos; // actually creating the object
// ...
cin >> gos;

或者,如果需要使用动态内存:

Baby * gos = new Baby();
// ...
cin >> *gos;

考虑使用智能指针来避免内存泄漏。

考虑这个片段

istream& operator>>(istream& is, Human* ref){
is>>ref->ageMonth;  //This gives error
return is;

第一个问题是需要传递引用,而不是指针。

istream& operator>>(istream& is, Human& ref){

严格来说,在这里使用指针并不是一个错误,只是一种很容易导致错误的糟糕做法。所以请使用参考资料。

第二个更大的问题是,你有一个Human,并试图使用ageMonth,而Human没有。

如果你知道你有Baby,就说:

 istream& operator>>(istream& is, Baby& ref){

如果你不知道你有哪种Human,你只能使用所有Human通用的东西。