当基类构造函数中需要传入参数进行构造时,定义子类构造函数时,构造相同名字的基类构造函数,对于基类也可以传入自身的参数
#include <iostream> using namespace std; class Animal{ public: void eat(); void sleep(); void drool(); Animal(string TheName);//子类的输入参数 string name; }; Animal::Animal(string TheName) { name = TheName; } void Animal::eat() { cout << "正在吃" << endl; } void Animal::sleep() { cout << "正在睡" << endl; } void Animal::drool() { cout << "正在留口水" << endl; } class Pig:public Animal{ public: Pig(string TheName, string TheSex); //TheName表示与父类相同的参数,TheSex表示子类独有的参数 string sex; void climb(); }; class Turbol:public Animal{ public: Turbol(string TheName, string TheSex); string sex; void swim(); }; Pig::Pig(string TheName, string TheSex) : Animal(TheName){ //TheName表示与父类相同的输入参数, TheSex表示子类独有的输入参数 sex = TheSex; } Turbol::Turbol(string TheName, string TheSex) : Animal(TheName){ sex = TheSex; } int main() { Pig pig("小猪猪", "女"); Turbol turtle("小甲鱼", "男"); cout << "世上每一只猪都叫" << pig.name << " 性别是" << pig.sex << endl; cout << "世上每一只乌龟都叫" << turtle.name << " 性别是" << turtle.sex << endl; }