gpt4 book ai didi

c++ - dynamic_cast 一个非常量引用到一个常量引用。 cppreference.com 的解释似乎很奇怪

转载 作者:行者123 更新时间:2023-11-28 03:01:06 24 4
gpt4 key购买 nike

我正在刷新我对可用的各种类型的转换的内存,并在 cppreference.com ( http://en.cppreference.com/w/cpp/language/dynamic_cast) 上看到以下内容:

1) If the type of expression is the exactly new_type or a less cv-qualified version of new_type, the result is expression.

引用结构

dynamic_cast < new_type > ( expression )

我将其解释为,例如,尝试对同一类型的常量引用进行非常量引用的动态转换实际上会产生非常量引用,因此允许我调用其非常量成员, 这与我的预期相反。我写了以下 noddy 代码来检查:

#include<iostream>

class Base
{
int value;
public:
Base():value(0){};

virtual void ShowVal() const
{
printf("Value is %d\n", value);
}

virtual void SetVal(int val)
{
value = val;
}

};

int main ()
{
Base b;
Base& rB = b;

b.ShowVal();

(dynamic_cast<const Base&>(rB)).SetVal(2); //fails where (dynamic_cast<Base&>(rB)).SetVal(2); is obviously fine.

b.ShowVal();
}

正如我所预料的那样,这个没有编译并且我得到了错误

blah.cpp:28:3: error: member function 'SetVal' not viable: 'this' argument has type 'const Base', but function is not marked const
(dynamic_cast<const Base&>(rB)).SetVal(2);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我想我想问的问题是:我是否误解了上述规则?如果是这样,它实际上在说什么,是否有类似的基本示例来证明它?

谢谢。 (同时我会再看一遍,如果我意识到我看错了,我会迅速删除这个问题并开始打脸...)

最佳答案

从写法来看不是很明显,但转换仍然发生。它只是意味着您从转换中获得的对象(指针或引用)与 expression 表示的对象相同。 cast 表达式是 const 类型,因为这是您将其转换为的类型。

这是它在 C++11 标准中的样子:

If the type of v is the same as T, or it is the same as T except that the class object type in T is more cv-qualified than the class object type in v, the result is v (converted if necessary).

注意“必要时转换”。

您可能想知道为什么它甚至会说结果是 expression?对于大多数 dynamic_cast,结果不是 expression。考虑从指向基类的指针转换为指向派生类的指针。你不会从中得到相同的指针。相反,您会得到一个指向派生子对象的指针。

关于c++ - dynamic_cast 一个非常量引用到一个常量引用。 cppreference.com 的解释似乎很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20829200/

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