在不转换对象的情况下调用子类方法
Call a subclass method without casting the object
我的 class 结构如下所示:
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
时,我都会得到 "Hello from class A" 输出,即使我将 class B 或 C 的实例作为参数传递也是如此。
我在这里做错了什么?
需要引用传递:
void doSomethingElse(const A& argument = A()) {
argument.doSomething();
}
如果不通过引用传递,则参数成为参数的副本,并且只复制参数的A
部分。 doSomething()
然后在 A
上被调用,而不是您最初作为参数传递的对象。
我的 class 结构如下所示:
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
时,我都会得到 "Hello from class A" 输出,即使我将 class B 或 C 的实例作为参数传递也是如此。
我在这里做错了什么?
需要引用传递:
void doSomethingElse(const A& argument = A()) {
argument.doSomething();
}
如果不通过引用传递,则参数成为参数的副本,并且只复制参数的A
部分。 doSomething()
然后在 A
上被调用,而不是您最初作为参数传递的对象。