用c++构造一个父亲类Father和一个儿子类Son,两个类中各有表示其各自年龄的数据成员,写一个友元函数,该函数可以计算出父子年龄总和。
时间: 2024-05-10 20:19:08 浏览: 24
以下是实现代码:
```cpp
#include <iostream>
using namespace std;
class Son; //提前声明子类
class Father {
private:
int f_age;
public:
Father() { f_age = 50; } //默认父亲年龄为50岁
Father(int age) { f_age = age; }
friend int sum_age(Father f, Son s); //友元函数声明
};
class Son {
private:
int s_age;
public:
Son() { s_age = 20; } //默认儿子年龄为20岁
Son(int age) { s_age = age; }
friend int sum_age(Father f, Son s); //友元函数声明
};
int sum_age(Father f, Son s) {
return f.f_age + s.s_age;
}
int main() {
Father f(60);
Son s(30);
cout << "Father's age: " << f.f_age << endl;
cout << "Son's age: " << s.s_age << endl;
cout << "Sum age: " << sum_age(f, s) << endl;
return 0;
}
```
在上面的代码中,我们声明了一个Father类和一个Son类,每个类都有一个表示其各自年龄的数据成员。我们还声明了一个友元函数sum_age,它可以访问Father和Son类的私有数据成员。在主函数中,我们创建了一个Father对象和一个Son对象,并调用sum_age函数计算出他们的年龄总和。