【问题标题】:Polymorphism? C++ vs Java多态性? C++ 与 Java
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 使用 virtual 限定符,它们仍然是成员函数。 C++ 不使用术语“方法”。有虚成员函数和非虚成员函数。不过,撇开术语不谈,答案是正确的。
  • 我永远不会和 Pete Becker 争论 C++。
  • 我忘了说,除了术语,这个答案是正确的。
【解决方案2】:

使用“虚函数”。

#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;
}

在Java中,所有的实例方法默认都是虚函数。

【讨论】:

    【解决方案3】:

    回答有点晚了,但是在派生类中使用override 关键字让编译器知道您正在覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 2012-12-23
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多