C++ 虚函数
如下
//父类定义的display方法没有virutal关键字,则子类调用其display方法时,实际上会执行父类的方法.子类运行该方法,结果将不会输出payment //父类定义该方法时如果加上virtual关键字,则子类运行结果将会输出payment //但是有几个问题需要思考 //1.如果父类没有实现该方法,且定义时没有加上virtual关键字 结果:编译不过 //2.如果父类没有实现该方法,且定义有加上virtual关键字 结果:编译不过 //关于以上两点,结论是,只有纯虚函数才能在父类中也不实现.关于纯虚函数的细节暂不清楚,既然是以使用为目的,其他的特性以后遇到的时候再来了解 #include"stdafx.h" #include<iostream> #include<string> using namespace std; class Student { public: Student(int num, string name, float score); virtual void display(); protected: int num; string name; float score; }; Student::Student(int num, string name, float score) { this->num = num; this->name = name; this->score = score; } void Student::display() { cout << " num: " << this->num; cout << " name: " << this->name; cout << " score: " << this->score << endl; } class Graduate : public Student { private: float payment; public: Graduate(int num, string name, float score, float payment); void display(); }; Graduate::Graduate(int num, string name, float score, float payment) :Student(num, name, score), payment(payment) {} void Graduate::display() { cout << " num: " << this->num; cout << " name: " << this->name; cout << " score: " << this->score; cout << " payment: " << this->payment << endl; } int main() { Student stu1(1001, "Li", 87.5); Graduate gra1(2001, "Wang", 98.5, 10000); Student *pt = &stu1; pt->display(); pt = &gra1; pt->display(); cin.get(); return 0; }
输出:
num: 1001 name: Li score: 87.5
num: 2001 name: Wang score: 98.5 payment: 10000
相关推荐
哈嘿Blog 2020-10-26
明月清风精进不止 2020-07-05
PythonMaker 2020-07-05
xirongxudlut 2020-06-28
kkpiece 2020-06-16
qscool 2020-06-12
CloudXli 2020-06-11
vs00ASPNET 2020-06-09
Dimples 2020-06-08
kuoying 2020-06-07
JJandYY 2020-05-31
Wyt00 2020-05-30
liuyh 2020-04-03
CloudXli 2020-05-11
世樹 2020-05-11
bizercsdn 2020-05-10
joyjoy0 2020-05-09