开发者

How to prevent compiler doing implicit typecasting in for the class constructor argument?

开发者 https://www.devze.com 2022-12-10 17:45 出处:网络
#include <iostream> using namespace std; str开发者_如何学Pythonuct testarray{ int element; public:
#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

0

精彩评论

暂无评论...
验证码 换一张
取 消