【发布时间】:2015-08-20 15:42:17
【问题描述】:
我有一些通过引用传递变量的代码,但不会像我期望的那样导致在调用代码中更新变量;
// Interface classes
class Animal{};
class Car{
public:
virtual void testDrive(Animal &animal) = 0;
};
// A specific implementation
class Bear : public Animal{
public:
int testthing = 0;
};
void Ferrari::testDrive(Animal &animal){
Bear b = dynamic_cast<Bear &>(animal);
b.testthing = 1;
}
// Use those classes, doesn't need to know about Bear or Ferrari
int main()
{
// Set up myCar and myAnimal
myCar.testDrive(myAnimal) // ** but myAnimal is unchanged! **
}
我实际上已经能够通过传递一个指针来让它工作(myAnimal 更新为testthing = 1),但我很想知道这里发生了什么。
据我了解,通过引用传递变量与传递指针密切相关,并且“关于多态性,引用就像指针一样工作”*。
那么为什么一个有效而另一个无效呢?有没有一种简单的方法可以让它与参考一起使用?
*Are references and pointers equal with regards to polymorphism?
编辑:这只是说明我的意思的一个例子,显然不是生产代码。
【问题讨论】:
-
P.S.:为熊驾驶汽车的混合比喻道歉;)
-
Bear b = dynamic_cast<Bear &>(animal);进行复制。你可能想要Bear& b = dynamic_cast<Bear &>(animal); -
好的,谢谢。指针似乎不会发生同样的情况,您能解释一下原因吗,以及是否有办法通过引用使其工作?
-
顺便说一句,谁投了反对票,我能问为什么吗?如果这个问题有问题,我想在以后避免它。
-
我猜
myCar和myAnimal缺少分号 + 缺少声明 = 否决票(虽然我只能猜测,不是我)
标签: c++