本文介绍了关于c ++中const_cast的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

all:
这是从Effective C ++第三版编辑中引用的

all: this is quoted from Effective C++ 3rd editiion

我的问题是可以const_cast添加constness到一个非const对象?
实际上我写了一个小程序试图批准我的想法。

My question is can const_cast add constness to a non-const object?Actually i wrote a small programme trying to approve my thought.

class ConstTest
{
 public:

 void test() {
    printf("calling non-const version test const function \n");
}

 void test() const{
    printf("calling const version test const function \n");

}

};
 int main(int argc,char* argv){
 ConstTest ct;
 const ConstTest cct;
 cct.test();
 const_cast<const ConstTest&>(ct).test();//it is wrong to write this statement without the '&',why

}

省略以下&'引起的错误:

Omitting the '&' incurs error below:

const_cast可以添加constness,但似乎你必须转换为对象引用,这个引用的神奇之处是什么?

It shows that const_cast can add constness,but seems like you have to cast to a object reference, what is the magic of this reference ?

推荐答案

您不需要 const_cast 添加constness:

You don't need const_cast to add constness:

class C;
C c;
C const& const_c = c;

另一方面需要一个 const_cast

const C const_c;
C& c = const_cast<C&>(const_c);

但是如果您尝试对 c使用非const操作,行为是未定义的

but behavior is undefined if you try to use non-const operations on c.

顺便说一句,如果你不使用引用,则对象的副本是:

By the way, if you don't use a reference, a copy of the object is to be made:

C d = const_c; // Copies const_c

这篇关于关于c ++中const_cast的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:06