// c_datastructure.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Student {
public:
Student(int n, string nam, float sco) :num(n), name(nam), score(sco) {}
~Student() {}
void display();
protected:
int num;
string name;
float score;
};
void Student::display() {
cout << " num : " << num << endl;
cout << " name : " << name << endl;
cout << " score : " << score << endl;
}
class Graduate :public Student{
public:
Graduate(int n, string nam, float sco, float w) :Student(n, nam, sco), wage(w) {}
void display();
private:
float wage;
};
void Graduate::display() {
cout << " num : " << num << endl;
cout << " name : " << name << endl;
cout << " score : " << score << endl;
cout << " wage : " << wage << endl;
}
int main()
{
cout << "************" << endl;
Student s(1001, "li", 87.33);
Graduate g(1002, "Wang", 33.12, 1222.3);
Student*str = &s;
str->display();
// (*str).display();
cout << endl << endl;
// 定义指向基类指针,这时候指向具体的对象
str = &g;
str->display();
// (*str).display();
// system("pause");
/*
int A[] = { 1, -2, 3, 10, -4, 7, 2 };
int maxSum = maxSubArray_baoli(A, 7);
cout << maxSum << endl;
cout << maxSubArray_fenzhi(A, 0, 7) << endl;
cout << maxSubArray_dongtaiguihua(A, 7) << endl;
*/
return 0;
}
该段代码中一开始定义了指向基类的指针str,一开始调用display()则调用Student基类的display函数,没有错误。但是后来引用了具体派生对象的g后,再次调用display()发现只是输出基类的信息,而派生类新增的对象成员wage则无法输出。这是和c++相关,那么这时候的派生类的引用地址其实和基类的内存是共用的,所以只能输出基类的信息。这时候想通过这种办法输出派生类的新增信息怎么办呢?下面就要使用到C++的虚函数多态性,虚函数也是为次而生。
// c_datastructure.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Student {
public:
Student(int n, string nam, float sco) :num(n), name(nam), score(sco) {}
~Student() {}
virtual void display();
protected:
int num;
string name;
float score;
};
void Student::display() {
cout << " num : " << num << endl;
cout << " name : " << name << endl;
cout << " score : " << score << endl;
}
class Graduate :public Student{
public:
Graduate(int n, string nam, float sco, float w) :Student(n, nam, sco), wage(w) {}
virtual void display();
private:
float wage;
};
void Graduate::display() {
cout << " num : " << num << endl;
cout << " name : " << name << endl;
cout << " score : " << score << endl;
cout << " wage : " << wage << endl;
}
int main()
{
cout << "************" << endl;
Student s(1001, "li", 87.33);
Graduate g(1002, "Wang", 33.12, 1222.3);
Student*str = &s;
str->display();
// (*str).display();
cout << endl << endl;
// 定义指向基类指针,这时候指向具体的对象
str = &g;
str->display();
// (*str).display();
// system("pause");
/*
int A[] = { 1, -2, 3, 10, -4, 7, 2 };
int maxSum = maxSubArray_baoli(A, 7);
cout << maxSum << endl;
cout << maxSubArray_fenzhi(A, 0, 7) << endl;
cout << maxSubArray_dongtaiguihua(A, 7) << endl;
*/
return 0;
}
这时候在基类中将void display()定义为虚函数:virtual void dispaly();那么就可以实现在派生类族中具有相同函数时候,通过指向基类指针或者引用基类,进而调用具体的派生对象实现不同的功能。从而避免了多次new派生对象去调用该共同函数,这也是多态性的重要体现。