在三个类上实现输入运算符重载,重载函数不能声明为类的友元,调用相应的set成员函数来实现数据传递。在子类的set函数中需要调用父类的set函数。
时间: 2024-05-11 08:14:13 浏览: 12
以下是一个可能的实现:
```c++
#include <iostream>
using namespace std;
class Animal {
protected:
string name;
int age;
public:
void set(string n, int a) {
name = n;
age = a;
}
virtual void print() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
class Cat : public Animal {
string color;
public:
void set(string n, int a, string c) {
Animal::set(n, a);
color = c;
}
void print() {
Animal::print();
cout << "Color: " << color << endl;
}
};
class Dog : public Animal {
string breed;
public:
void set(string n, int a, string b) {
Animal::set(n, a);
breed = b;
}
void print() {
Animal::print();
cout << "Breed: " << breed << endl;
}
};
istream& operator>>(istream& is, Animal& a) {
string n;
int ag;
is >> n >> ag;
a.set(n, ag);
return is;
}
istream& operator>>(istream& is, Cat& c) {
Animal& a = c;
is >> a;
string col;
is >> col;
c.set(a.name, a.age, col);
return is;
}
istream& operator>>(istream& is, Dog& d) {
Animal& a = d;
is >> a;
string br;
is >> br;
d.set(a.name, a.age, br);
return is;
}
int main() {
Cat c;
Dog d;
cout << "Enter cat's name, age, and color: ";
cin >> c;
cout << "Enter dog's name, age, and breed: ";
cin >> d;
cout << endl << "Cat:" << endl;
c.print();
cout << endl << "Dog:" << endl;
d.print();
return 0;
}
```
在这个例子中,Animal类是一个基类,Cat和Dog类是它的两个子类。在Animal类中定义了一个set函数,用于设置姓名和年龄。Cat和Dog类都继承了这个函数,并增加了自己的数据成员。它们也都定义了一个print函数,用于输出所有数据成员。
在主函数中,我们定义了一个Cat对象和一个Dog对象,并且通过输入运算符重载来从标准输入读取数据。输入运算符重载函数使用相应的set函数来设置数据成员。注意,在Cat和Dog的set函数中,我们调用了Animal的set函数来设置姓名和年龄。
最后,我们输出所有数据成员,使用的是各自的print函数。注意,在Cat和Dog的print函数中,我们调用了Animal的print函数来输出姓名和年龄。这里使用了虚函数的特性,使得程序能够正确地调用各自的print函数。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)