C++中的虚函数和多态的关系
2005-06-28 11:26
633 查看
我的小例子:
#include
using namespace std;
class A{
private:
int numA;
public:
A();
virtual void prt(); //看到virtual function就要想到要使用多态机制了!
};
A::A(){
cout << "Construct in A" << endl;
}
void A::prt(){ //virtual function在定义体的外部实现的时候,不要加virtual关键字
cout << "prt in A" << endl;
}
class B : public A{
private:
int numB;
public:
B();
void prt();
};
B::B() : A(){
cout << "Construct in B" << endl;
}
void B::prt(){
cout << "prt in B" << endl;
}
int main()
{
A *arryA = new A();
A *arryB = new B();
arryA->prt();
arryB->prt(); //使用多态机制
arryB->A::prt(); //不使用多态机制
delete arryA;
delete arryB;
return 0;
}
#include
using namespace std;
class A{
private:
int numA;
public:
A();
virtual void prt(); //看到virtual function就要想到要使用多态机制了!
};
A::A(){
cout << "Construct in A" << endl;
}
void A::prt(){ //virtual function在定义体的外部实现的时候,不要加virtual关键字
cout << "prt in A" << endl;
}
class B : public A{
private:
int numB;
public:
B();
void prt();
};
B::B() : A(){
cout << "Construct in B" << endl;
}
void B::prt(){
cout << "prt in B" << endl;
}
int main()
{
A *arryA = new A();
A *arryB = new B();
arryA->prt();
arryB->prt(); //使用多态机制
arryB->A::prt(); //不使用多态机制
delete arryA;
delete arryB;
return 0;
}
相关文章推荐
- c++中的虚函数和多态之间的关系
- c++中的虚函数和多态之间的关系
- C++ 虚函数使用注意点 与 多态的关系
- C++多态:虚函数、指针、虚函数表
- C++_多态与虚函数
- C++语法细微(五)(多态虚函数)
- C/C++指针,多态,函数参数,面向对象抽象
- [C++] 如何不用虚函数实现多态
- C++学习总结系列--虚函数与多态
- 对C++中虚函数、纯虚函数在多态中作用的一点认识
- C/C++ 函数调用关系图
- C++中的多态与虚函数的内部实现
- c++多态中的虚函数
- C++ 多态与虚函数
- C++中利用虚函数实现多态
- C++中的虚函数的作用主要是实现了多态的机制
- 多态与虚函数编程题 #2(C++程序设计第6周)
- C++多态部分以及虚函数虚表总结
- C++ 成员函数与成员变量的关系
- C++之多态和虚函数