使用c ++生成const对象

Mei*_*eir 1 c++ casting

说每次使用强制转换时,生成的对象是一个const对象是否正确?

...因此,如果该函数将其作为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
Run Code Online (Sandbox Code Playgroud)

(当然,如果f(....)按值接收参数,那么它将获得一个非常可用的非const版本)

Fai*_*ali 12

通常,当某种类型的对象转换为另一种类型的对象(非引用类型)时,会创建一个临时对象(而不是const对象).临时对象(不可见,无名,右值)只能绑定(在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
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.