强制转换c++中通过引用传递的变量
Casting a variable passed by reference in 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
更新),但我有兴趣知道这里发生了什么。
根据我的理解,通过引用传递变量与传递指针密切相关,并且"就多态性而言,引用就像指针一样工作"*。
那么为什么一个有效而另一个无效呢?有没有一种简单的方法可以让它与引用一起工作?
*引用和指针在多态性方面是相等的吗?
编辑:这只是一个例子,以显示我的意思,显然不是生产代码。
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
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++方法中的引用变量
- 作为赋值(增加引用变量)C++的左操作数所需的左值
- 使用更改此变量的函数在同一行中打印引用变量
- 将延迟变量分配给引用变量
- 如何通过引用获取引用变量的地址?
- 将引用变量传递给函数
- C++中引用变量的内存?
- 按名称存储和引用变量列表
- 返回一个C++引用变量 VS 返回一个变量
- c++ 在 if 语句中分配引用变量
- 引用变量何时合适,为什么?你能解释一下实际的语法和位置吗?
- C++ - 将一个变量分配给另一个变量和将变量分配给引用变量有什么区别?
- 在类范围内声明时,应在 C++14 中引用变量模板
- 当引用变量的引用"死亡"时,它会发生什么?
- 将非按引用变量分配给返回按引用的函数,反之亦然
- 引用变量如何存储在mem中
- 引用变量存储在哪里