码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 虚函数

时间:2017-12-16 11:23:28      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:不清楚   include   oat   prot   protected   编译不过   log   virtual   关于   

如下

//父类定义的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

C++ 虚函数

标签:不清楚   include   oat   prot   protected   编译不过   log   virtual   关于   

原文地址:http://www.cnblogs.com/heben/p/8045339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!