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,都出现编译错误。
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,都出现编译错误。
相关文章推荐
- c++和java中关于如何调用父类方法和子类方法的辨析
- c++ 子类调用父类构造方法 调用父类方法 类声明与实现分离
- c++多态,子类和父类方法的调用
- 关于C++中子类调用父类方法的一个问题
- c++与java中子类中调用父类成员的方法
- C++和JAVA中一些区别,包括指向子类的引用会调用谁的方法,子类构造函数自动调用父类构造函数时,父构造会调用的谁方法
- 关于C++中子类调用父类方法的一个问题
- C语言使用技巧3:C++中子类调用父类重载函数的方法
- C++关于子类调用父类的构造方法的问题
- 子类调用父类方法:c++和java的不同
- C++ 子类B重载父类A的方法funA后,在父类A中调用funA会调用子类B还是父类A的funA方法?
- Java里子类调用父类构造方法问题
- 父类调用子类方法
- 子类继承父类(父类和子类里:块、静态块、构造和方法覆写)之间调用顺序
- python子类调用父类的方法-super
- 子类调用父类构造方法示例
- OC中继承子类对象调用方法机制 子类对象访问父类中的实例变量
- java创建一个子类对象是会调用父类的构造方法会不会创建父类
- 子类虚函数C++ 继承中子类与父类虚函数入栈顺序 及父类私有虚函数的调用方式