java - 多态性? C++ 与 Java

标签 java c++ 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;
}

结果:

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

不确定是我做错了什么,还是这与语言本身有关?

最佳答案

您需要阅读 C++ 的 virtual 关键字。如果没有该限定符,您所拥有的就是对象中的成员函数。它们不遵循多态性(动态绑定(bind))规则。使用 virtual 限定符,您可以获得使用动态绑定(bind)的方法。在 Java 中,所有实例函数都是方法。你总是会得到多态性。

关于java - 多态性? C++ 与 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34445553/

相关文章:

ios - Objective-C 函数通过在方法签名中指定关系来更新 Core Data 关系

nhibernate - 使用 NHibernate 正确映射多态关系

java - 在 run() 方法中使用 return 会发生什么?

java - 该查询的 Hibernate 等效项是什么?(添加两列)

java - 我刚刚检索到的对象上的 Hibernate StaleObjectStateException

C++:循环菜单切换

c++ - 在 VC++ 中将 unsigned long 转换为 int?

c++ - 为什么具有继承构造函数的类也会获得合成的默认构造函数?

java - CSVRecordReader 和 CSV 行末尾未终止的引用字段

c# - C#是否可以将基类的实例用于子类的不同实例?