How to prevent compiler doing implicit typecasting in for the class constructor argument?
#include <iostream>
using namespace std;
str开发者_如何学Pythonuct testarray{
int element;
public:
testarray(int a):element(a){}
};
class myarray
{
public:
testarray i;
public:
myarray(testarray a) : i(a){ }
} ;
int main()
{
myarray objArray[3] = {1,2,3};
return 0;
}
The above code compiles fine in Visual C++ 2005 Express Edition IDE. But what I want is to prevent the compiler from implicitly typecasting the object type.
Use the keyword explicit
for testarray
constructor so that the compiler doesn't perform implicit conversions. Basically you need to write the constructor as:
explicit testarray(int a):element(a){}
You can use explicit
keyword for your struct constructor.
yes, use the keyword "explicit" as stated above. one more suggestion about the source you've provided: why do you have the "public" in the struct? All struct's members are public by default. if you want to have smth with different access modifiers (say, several "private" members or methods), you're better off to use classes.
Perhaps you want the constructor to be explicit
?
http://www.cppreference.com/wiki/keywords/explicit
精彩评论