强制转换c++中通过引用传递的变量

Casting a variable passed by reference in C++

本文关键字:引用 变量 转换 c++      更新时间:2023-10-16

我有一些代码通过引用传递变量,但不导致变量在调用代码中被更新,因为我希望;

// 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! **
}

我实际上已经能够通过传递指针来实现这一工作(myAnimaltestthing = 1更新),但我有兴趣知道这里发生了什么。

根据我的理解,通过引用传递变量与传递指针密切相关,并且"就多态性而言,引用就像指针一样工作"*。

那么为什么一个有效而另一个无效呢?有没有一种简单的方法可以让它与引用一起工作?

*引用和指针在多态性方面是相等的吗?

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

Bear b = dynamic_cast<Bear &>(animal);animal强制转换值的值副本,因此对b的修改不会影响原始值。

你想要Bear& b = dynamic_cast<Bear &>(animal);代替。那么b本身就是一个引用。

注意,如果dynamic_cast在进行引用强制转换时失败,则会抛出std::bad_cast。你应该妥善处理

我不是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