【发布时间】:2012-01-18 08:06:38
【问题描述】:
如何通过基类对象访问派生类的功能? 我已经编译并运行了程序,没有任何错误(vs2010 express edition)。 任何人都可以澄清这个话题吗?
#include <iostream>
using namespace std;
class A {
public:
void f1() { cout << " f1 \n"; }
};
class B : public A{
int x;
public:
void f2(int x) {this->x = x; cout << "f2 " << this->x <<"\n";}
};
int main(int argc, char * argv[])
{
A * aaa = new A(); // created a base instance
B * b = (B *) aaa; // typecasted it to derived class
b->f2(5); // try to access function, which should not be possible (run-time error?)
return 0;
}
--> 输出
f2 5 // which concept is supports this output?
【问题讨论】:
标签: c++