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;
}
运行结果:
分类:
C++基础第一卷
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探