【发布时间】:2015-12-24 00:03:56
【问题描述】:
作为初学者尝试多态性。我想我正在尝试不同语言的相同代码,但结果不一样:
C++
#include <iostream>
using namespace std;
class A {
public:
void whereami() {
cout << "You're in A" << endl;
}
};
class B : public A {
public:
void whereami() {
cout << "You're in B" << endl;
}
};
int main(int argc, char** argv) {
A a;
B b;
a.whereami();
b.whereami();
A* c = new B();
c->whereami();
return 0;
}
结果:
You're in A
You're in B
You're in A
Java:
public class B extends A{
void whereami() {
System.out.println("You're in B");
}
}
//and same for A without extends
//...
public static void main(String[] args) {
A a = new A();
a.whereami();
B b = new B();
b.whereami();
A c = new B();
c.whereami();
}
结果:
You're in A
You're in B
You're in B
不确定是我做错了什么,还是与语言本身有关?
【问题讨论】:
-
您在第一个程序中的
whereami中缺少virtual关键字... -
@Reimeus:OP 也忘记在 Base 类中提供虚拟析构函数并写 delete c;在 main() 函数中。
标签: java c++ polymorphism comparison