posts - 137,comments - 0,views - 40818

Father.h:

复制代码
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Father
{
public:
    Father();
    Father(const string &name,int age);
    string getName();
    int getAge();
    string description();
private:
    string name;
    int age;
};
复制代码

Father.cpp:

复制代码
#include "Father.h"
#include <string>
#include <sstream>
using namespace std;
Father::Father() {
    name = "小熊猫";
    age = 10;
}
Father::Father(const string& name, int age) {
    cout << __FUNCTION__ << endl;
    this->name = name;
    this->age = age;
}
string Father::getName() {
    return name;
}
int Father::getAge() {
    return age;
}
string Father::description() {
    stringstream ret;
    ret << "姓名:" << name << " 年龄:" << age ;
    return ret.str();
}
复制代码

Son.h:

复制代码
#pragma once
#include <string>
#include "Father.h"
using namespace std;
class Son:public Father
{
public:
    Son(const string& name,int age,const string& game);
    string getGame();
    string description();
private:
    string game;
};
复制代码

Son.cpp:

复制代码
#include "Son.h"
#include <string>
#include <sstream>
using namespace std;
string Son::getGame() {
    return game;
}
Son::Son(const string &name, int age, const string &game):Father(name,age) {
    //若没有显式的调用父类的构造函数,那么将会自动调用父类的默认构造函数
    cout << __FUNCTION__ << endl;
    this->game = game;
}
string Son::description() {
    stringstream ret;
    ret << "姓名:" << getName() << " 年龄:" << getAge() << " 游戏:" << game;
    return ret.str();
}
复制代码

main.cpp:

复制代码
#include <iostream>
#include <string>
#include "Father.h"
#include "Son.h"
int main() {
    Father wjl("老王", 68);
    Son wsc("小王",25,"电竞");
    
    cout << wjl.description() << endl;
    cout << wsc.description() << endl;

    system("pause");
    return 0;
}
复制代码

运行结果:

posted on   wshidaboss  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示