注意:
1、子类的成员函数中,不能访问从父类继承的private成员。
2、子类、一般会添加自己的数据成员/成员函数,
或者重新定义从父类继承的方法!!!子类就会调用自己重新定义的方法,不会调用父类同名的方法。
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;
cout << son.getName() << "从事的职业是:" << son.getGame() << endl;
}
son头文件
#pragma once
#include "Father.h"
class Son :
public Father
{
public:
Son(const string &name, const int &age, const string &game);
string getGame();
string description();
private:
string name;
int age;
string game;
};
son.cpp文件
#include "Son.h"
#include<sstream>
Son::Son(const string & name, const int & age, const string & game):Father(name,age)
{
this->game = game;
}
string Son::getGame()
{
return game;
}
string Son::description()
{
stringstream ret;
ret << "姓名:" << getName() << " 年龄:" << getAge() << " 职业:" << getGame();
return ret.str();
}
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();
}