标签:print amp 数据 参数初始化 类继承 初始 void run tco
如果一个类里面只有纯虚函数,没有其他成员函数和数据成员,就是接口类。
class Person {
public:
virtual void eat()=0;//纯虚函数
virtual void run()=0;//纯虚函数
};
Teacher 继承自接口类Person,并实现Person纯虚函数
//.h定义
class Teacher :public Person{
public:
virtual void eat();
virtual void run();
Teacher(string code);
void printCode();
protected:
string m_strCode;
};
//.cpp 实现
void Teacher::eat() {
cout<<"Teacher::eat()"<<endl;
}
void Teacher::run() {
cout<<"Teacher::run()"<<endl;
}
void Teacher::printCode() {
cout << "Teacher::printCode: " << m_strCode << endl;
}
Student类继承自Teacher,相当于有两个父类
//.h 定义
class Student : public Teacher {
public:
Student(string code);
virtual void eat();
virtual void run();
};
//.cpp 实现
void Student::run() {
cout << "Student::run()" << endl;
}
Student::Student(string code) : Teacher(code) { //列表参数初始化
}
void Student::eat() {
cout << "Student::eat()" << endl;
}
void personTest(Person *p1, Person *p2) {
p1->eat();
p1->run();
p2->eat();
p2->run();
}
int main() {
Student p1("001");
Student p2("002");
p1.printCode();
p2.printCode();
personTest(&p1, &p2);
return 0;
}
Teacher::printCode: 001
Teacher::printCode: 002
Student::eat()
Student::run()
Student::eat()
Student::run()
让Student 有两个父类,多重继承
class Teacher { //Teacher 不继承接口类Person
public:
Teacher(string code);
void printCode();
protected:
string m_strCode;
};
class Student : public Teacher ,public Person{ //由Student类来继承自接口类,并实现
public:
Student(string code);
virtual void eat();
virtual void run();
};
void personTest(Teacher *p1, Teacher *p2) {
p1->printCode();
p2->printCode();
}
int main() {
Student p1("001");
Student p2("002");
personTest(&p1, &p2);
return 0;
}
Teacher::printCode: 001
Teacher::printCode: 002
标签:print amp 数据 参数初始化 类继承 初始 void run tco
原文地址:https://www.cnblogs.com/wuyanzu/p/11874364.html