gpt4 book ai didi

c++ - 在 C++ 中转换生成 const 对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:10:34 25 4
gpt4 key购买 nike

这样说是否正确,无论何时使用转换,结果对象都是常量对象?

...因此只能用作函数的参数,如果函数接受它作为 const 对象?

例如

class C1 {
public: C1(int i=7, double d = 2.5){};
};

void f(C1& c) {};

int main(){
f(8);
return 1;
}
//won't compile

(当然,如果 f(....) 按值接收参数,那么它会得到一个非常量版本它可以使用)

最佳答案

通常当某种类型的对象转换为另一种类型(非引用类型)的对象时,会创建一个临时对象(不是const对象)。临时对象(不可见、无名、右值)只能绑定(bind)(在 C++98/03 中)为 const 的引用(称为“异常对象”的临时对象除外)。因此,创建临时对象的转换结果只能用作函数的参数,该函数要么接受它作为 const 引用,要么作为它可以被复制/转换成的类型。

例如

void f(double);  // 1
void f(const int&); // 2
void f(int&); // 3

struct B { B(int) { } };
struct C { C(int) { } };
void f(B b); // 4
void f(B& b); // 5
void f(const C& c); //6
void f(C& c); // 7

// D inherits from B
struct D : B { D(int) : B(0) { } };
void f(D& d); // 8

int main()
{
f( (int) 3.0 ); // calls 2, NOT 3
f( (float) 3 ); // calls 1 - const reference requires the same type
f( 1 ); // calls 2, NOT 3

f( (B) 1 ); // calls 4, not 5 - can accept it by non-const value
f( (C) 1 ); // calls 6, not 7 - can accept it by const-reference

f( (D) 1 ); // calls 4, not 8 - since a 'D' temporary object can be converted to a 'B' object - but will not bind to a non-const reference
}

希望对您有所帮助。

关于c++ - 在 C++ 中转换生成 const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1092972/

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