main主函数
#include<iostream>
#include"Father.h"
#include"Son.h"
int main()
{
Father father("大刚", 35);
Son son("小刚", 12, "电脑");
cout << father.description() << endl;
cout << son.description() << endl;
}
Father头文件
#pragma once
#include<string>
using namespace std;
class Father
{
public:
Father(const string &name, const int &age);
string getName()const;
int getAge()const;
string description()const;
private:
string name;
int age;
};
Father.cpp文件
#include "Father.h"
#include<sstream>
Father::Father(const string & name, const int & age)
{
this->name = name;
this->age = age;
}
string Father::getName()const
{
return name;
}
int Father::getAge()const
{
return age;
}
string Father::description() const
{
stringstream ret;
ret << "name:" << name << "age:" << age;
return ret.str();
}
Son头文件
#pragma once
#include "Father.h"
class Son :
public Father
{
public:
Son(const string &name, const int &age, const string &game);
string getGame();
private:
string name;
int age;
string game;
};
son.cpp文件
#include "Son.h"
Son::Son(const string & name, const int & age, const string & game):Father(name,age)
{
this->game = game;
}
string Son::getGame()
{
return game;
}
需要注意的是Son::Son(const string & name, const int & age, const string & game):Father(name,age)
{
this->game = game;
}
这里是将儿子里面的name,age传给后面的Father括号里面的name,age然后调用父类 的构造函数,下面的game是调用自己的构造函数。
2、子类继承父类里除了构造函数和析构函数所有的东西。