【问题标题】:Call a subclass method without casting the object调用子类方法而不强制转换对象
【发布时间】:2015-12-25 19:58:05
【问题描述】:

我的类结构如下所示:

class A {
public:
     A();

     virtual void doSomething() {
         qDebug() << "Hello from class A";
     }
};

class B : public A {
public:
    B();

    void doSomething() {
        qDebug() << "Hello from class B";
    }
};

class C : public A {
public:
    C();

    void doSomething() {
        qDebug() << "Hello from class C";
    }
};

在其他地方我有这样的方法:

void doSomethingElse(const A argument = A()) {
    argument.doSomething();
}

每次调用doSomethingElse 时,我都会得到“来自A 类的Hello”输出,即使我将B 类或C 类的实例作为参数传递。 我在这里做错了什么?

【问题讨论】:

标签: c++ inheritance subclass


【解决方案1】:

需要通过引用传递:

void doSomethingElse(const A& argument = A()) {
    argument.doSomething();
}

如果不通过引用传递,则参数成为参数的副本,并且仅复制参数的A 部分。然后在 A 上调用 doSomething(),而不是您最初作为参数传递的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多