当前位置:网站首页>Colon function and explicit keyword in constructor

Colon function and explicit keyword in constructor

2022-04-23 21:57:00 Three stone orders

The colon in the constructor functions , Class assigns values to member variables , Constants that are more suitable for member variables const type .

class myClass
{
    /* The colon in the constructor functions , Class assigns values to member variables , Constants that are more suitable for member variables const type .*/
public :
    myClass();//  Constructors , No return type , You can have a list of parameters , There is no need for 
    ~myClass();//  Destructor 
    int a;
    const int b;
}

myClass::myClass():a(1),b(1)//  Initialization list 
{
    
}

myClass::myClass()
{
    
    a = 1;//  you 're right , The effect is equivalent to initializing in the initialization list 
    b = 1;//  error ,const Variables cannot be assigned ;
}


Constructor with explicit keyword , Disable implicit conversion , That is, when calling this class, you must declare that it is a class ; Without this keyword, you can directly assign the data type value in the constructor

class AAA
{
    
public:
	//AAA(int a) : num(a) {}
	explicit AAA(int a) : num(a) {
    }
	int GetValue() {
     return num; }
private:
	int num;
};

int fun(AAA aaa)
{
    
	return (int)aaa.GetValue() + 1;
}

int main()
{
    
	//int a = fun(5);
	int a = fun(AAA(5));
}

版权声明
本文为[Three stone orders]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204200615437072.html