gpt4 book ai didi

c++ - 常量引用有何不同?

转载 作者:行者123 更新时间:2023-11-30 01:45:28 27 4
gpt4 key购买 nike

我不明白为什么下面的代码不起作用:

#include <iostream>
using namespace std;

class PayOff{};
class PayOffCall : public PayOff{};

class PayOffBridge{
public:
PayOffBridge( PayOff& innerPayOff){};
};

class VanilaOption{
public:
VanilaOption(PayOffBridge& ThePayOff_){cout << " test " <<endl;}
};


int main () {
PayOffCall thePayOff;
VanilaOption theOption(thePayOff);
return 0;
}

出于某种原因,更改 VanilaOption 类(下面的代码)中对 const 的引用使其工作,有人可以解释它是如何工作的吗?我得到的错误是:没有匹配函数来调用 'VanilaOption::VanilaOption(PayOffCall&)'

但这并不能帮助我弄明白。

class VanilaOption{
public:
VanilaOption(const PayOffBridge& ThePayOff_){cout << " test " <<endl;}
};

我也不明白为什么在预期 PayOffBridge 引用有效时传递 PayOffCall 引用,有人可以帮我解决这个问题吗?

谢谢!

最佳答案

原始代码不起作用,因为 thePayOff不是 PayOffBridge 类型的值, 而不是 PayOffCall 类型.

修改后的代码可以工作,因为它允许构建一个临时的 PayOffBridge来自 PayOff 的对象PayOffCall 的子对象对象,然后构造 VanillaOption来自那个临时对象。那是因为:

  1. PayOffBridge构造函数是非显式的,
  2. 派生类的左值可以转换为其任何可访问基类的左值,并且
  3. 因为临时对象可以绑定(bind)到 const 左值引用(但不能绑定(bind)到非 const 左值引用)。

换句话说,const 引用版本允许这样的代码:

VanilaOption theOption(PayOffBridge(thePayOff));
// ^^^^^^^^^^^^^^^^^^^^^^^-----< temporary

而对于非常量版本,您需要一个可变的左值,可能像:

PayOffBridge b(thePayOff);
VanilaOption theOption(b);
// ^----- lvalue

关于c++ - 常量引用有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34583750/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com