在C ++中转换通过引用传递的变量

时间:2015-08-20 15:42:18

标签: c++

我有一些代码通过引用传递变量,但是没有像我期望的那样导致变量在调用代码中更新;

// 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),但我有兴趣知道&#39 ; s继续在这里。

据我所知,通过引用传递变量与传递指针非常密切相关,并且&#34;关于多态性,引用就像指针一样工作&#34; *。

那为什么一个工作而另一个不工作呢?是否有一种简单的方法可以使用引用?

* Are references and pointers equal with regards to polymorphism?

编辑:这只是一个展示我意义的例子,显然不是生产代码。

2 个答案:

答案 0 :(得分:5)

Bear b = dynamic_cast<Bear &>(animal);正在获取animal投射值的值副本,因此对b的修改不会影响原始版本。

您想要Bear& b = dynamic_cast<Bear &>(animal);。然后b本身就是一个参考。

请注意,如果dynamic_cast在进行参考投射时失败,则会引发std::bad_cast。你应该妥善处理。

答案 1 :(得分:0)

我不能100%确定问题是什么。正常铸造工作正常:

#include <iostream>
using namespace std;
// Interface classes
class Animal{};

class Car{
public:
    virtual void testDrive(Animal &animal) = 0;
};

class Ferrari : public Car {
public:
    void testDrive(Animal &animal);
};


// A specific implementation
class Bear : public Animal{
public:
    int testthing = 0;
};


    void Ferrari::testDrive(Animal &animal){
        Bear & b = (Bear &) animal;

        b.testthing = 1;
    }


// Use those classes, doesn't need to know about Bear or Ferrari
int main()
{
// Set up myCar and myAnimal
    Animal myAnimal;
    Ferrari myCar ;
myCar.testDrive(myAnimal);  // ** but myAnimal is unchanged! **
cout << ((Bear &)myAnimal).testthing ;

}

打印: 1