我正在更改一个过去采用整数参数的旧例程,以便它现在采用对象的const引用.我希望编译器能告诉我调用函数的位置(因为参数类型错误),但是对象有一个构造函数,它接受一个整数,所以编译器创建一个临时对象,而不是失败,传递给它整数,并将对它的引用传递给例程.示例代码:
class thing {
public:
thing( int x ) {
printf( "Creating a thing(%d)\n", x );
}
};
class X {
public:
X( const thing &t ) {
printf( "Creating an X from a thing\n" );
}
};
int main( int, char ** ) {
thing a_thing( 5 );
X an_x( 6 );
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我希望该X an_x( 6 )行不能编译,因为没有X构造函数需要int.但它确实编译,输出如下:
Creating a thing(5)
Creating a thing(6)
Creating an X from a thing
Run Code Online (Sandbox Code Playgroud)
如何保留thing( int )构造函数,但不允许临时对象?
Pao*_*sco 11
explicit在事物构造函数中使用关键字.
class thing {
public:
explicit thing( int x ) {
printf( "Creating a thing(%d)\n", x );
}
};
Run Code Online (Sandbox Code Playgroud)
这将阻止编译器在找到整数时隐式调用thing构造函数.