C++中的类继承的问题
2014-10-31 22:56
106 查看
#include <iostream> using namespace std; static int x; class A { public: A() {x = 1;} virtual ~A(){x = 2;} virtual void foo() {x = 3;} }; class B :public A { public: B(){x = 4;} virtual ~B(){x = 5;} void foo(){x = 6;} void bar(){foo();} }; class C:public B { public: C() {x = 7;} virtual ~C(){x = 8;} void foo() {x = 9;} void bar(){foo();} }; C testc; void main(void) { A *testa = NULL; B *testb = NULL; testa = (A*)&testc; cout << x << endl; testa->foo(); cout << x << endl; ((B)testc).bar(); cout << x << endl; testb = new B; cout << x << endl; testb->foo(); cout << x << endl; delete testb; cout << x << endl; ((B*)(&testc))->bar(); cout << x << endl; testa = NULL; cout << x << endl; }
输出为:
7
9
2
4
6
2
9
9
第三个输出很奇怪,原来 是((B)testc).bar(),原来先转换成一个临时对象,调用bar后会析构,最终调用基类的析构函数
倒数第二个输出,虽然bar不是虚函数,但是当中调用了foo这个虚函数,还是会根据动态类型找到C的foo
相关文章推荐
- C++的继承参数问题
- 在C++的虚继承中要注意的一个传值问题
- C++多重继承的一些问题
- 深入剖析C++继承,多态以及隐藏(三)(类层次中的转化问题)
- C++继承体系中名字遮挡问题
- C++继承、虚继承、虚函数类的大小问题
- C++模板继承在g++编译中应注意的问题(if you use `-fpermissive', G++ will accept your code, but allowing the use ...)
- C++中 public和private派生类继承问题和访问权限问题
- C++多重继承相关问题
- 多继承实现COM类中的"菱形问题" C++也有一样的菱形问题
- 有个C++虚继承的问题
- 深入剖析C++继承,多态以及隐藏(三)(类层次中的转化问题)
- C++派生继承中的一个问题!
- C++学习笔记(8)——继承中的二义性问题和虚基类
- 关于C++中私有继承后虚函数的访问权限与私有继承后多态的问题
- C++里面多继承带来的指针漂移问题(转)
- C++中 public和private派生类继承问题和访问权限问题
- C++基础——多继承问题
- C++中 public和private派生类继承问题和访问权限问题
- 关于C++虚函数默认参数的问题。Effective C++ 条款38: 决不要重新定义继承而来的缺省参数值