c++中的多态性和运算符重载混淆
Polymorphism and operator overloading confusion in c++
我不知道如何用我在上面定义的>>
运算符读取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
通用的东西。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用