ivi*_*viO 5 c++ java polymorphism comparison
尝试将多态性作为初学者.我想我正在尝试使用不同语言的相同代码,但结果并不相同:
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;
}
Run Code Online (Sandbox Code Playgroud)
结果:
You're in A
You're in B
You're in A
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
结果:
You're in A
You're in B
You're in B
Run Code Online (Sandbox Code Playgroud)
不确定我做错了什么,或者这与语言本身有什么关系?
小智 9
您需要阅读有关virtualC++ 的关键字.没有该限定符,您拥有的是对象中的成员函数.它们不遵循多态性规则(动态绑定).使用virtual限定符,您将获得使用动态绑定的方法.在Java中,所有实例函数都是方法.你总是得到多态性.
使用“虚拟功能”。
#include <iostream>
using namespace std;
class A {
public:
virtual void whereami() { // add keyword virtual here
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;
}
Run Code Online (Sandbox Code Playgroud)
在Java中,默认情况下,所有实例方法都是虚函数。