如何通过基类对象访问派生类的函数? 我已编译并运行该程序没有任何错误(vs2010 express版)。 任何人都可以澄清这个话题吗?派生类访问的基类 - 如何?
#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?
谢谢Coder02,我知道有各种铸造关键字为C++,但我从来没有想过,我是执行C风格的类型转换。 谢谢大家的回复。这是一个很好的帮助:) – fadedreamz 2012-01-18 19:34:09
不要让这个错误 - C风格的转换并不总是很糟糕,并不总是导致C++中的未定义结果 - 它只是在你的情况下,因为A不会继承B. @ Anders已经回复了这在内存中的样子,以及为什么结果在这种情况下是未定义的。 – Coder02 2012-01-19 07:06:09