您的位置:首页 > 编程语言 > C语言/C++

c++ 父类和子类的方法调用

2012-12-29 10:46 363 查看
#include<iostream>

using namespace std;

class Father{

public:

int getNum(){

return 1;

}

private:

int Num;

};

class Child:public Father{

public:

int getNum(){

return Num;

}

int static const Num = 10;

};

int main(){

int i=0;

int j = 0;

Father *father = new Child();

Father *father1 = new Father();

//Child *child1 = new Father();

i = father->getNum();

j = father1->getNum();

cout<<i<<" "<<j<<endl;
}

输出是1 1



#include<iostream>

using namespace std;

class Father{

public:

virtual int getNum(){

return 1;

}

private:

int Num;

};

class Child:public Father{

public:

int getNum(){

return Num;

}

int static const Num = 10;

};

int main(){

int i=0;

int j = 0;

Father *father = new Child();

Father *father1 = new Father();

//Child *child1 = new Father();

i = father->getNum();

j = father1->getNum();

cout<<i<<" "<<j<<endl;

}

输出是:10 1

如果将//Child *child1 = new Father();打开 , 无论方法是否virtual,都出现编译错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: