C++11新特性之 explict
作者:互联网
C++11新特性之 explict
目的
指定构造函数或转换函数为显示,即不能用于隐式转化;
语法
一般出现在类定义之内的构造函数中;
如:
class P
{
explict P(){};
};
代码示例
#include <iostream>
class Test
{
public:
Test(int a):a_(a)
{
std::cout << "Test()" << std::endl; // 通过打印看调用几次构造函数
}
int Get_Data()
{
return a_;
}
Test operator + (Test t)
{
return Test(a_ + t.a_);
}
private:
int a_;
};
int main()
{
Test t1{3};
Test t2 = t1 + 5; // 5 会隐式的调用的Test构造函数
std::cout << t2.Get_Data() << std::endl; //输出 8
}
在上一个的例子的基础之上加上 explict
#include <iostream>
class Test
{
public:
explicit Test(int a):a_(a)
{
std::cout << "Test()" << std::endl; // 通过打印看调用几次构造函数
}
int Get_Data()
{
return a_;
}
Test operator + (Test t)
{
return Test(a_ + t.a_);
}
private:
int a_;
};
int main()
{
Test t1{3};
Test t2 = t1 + 5; //error
// error: no match for 'operator+' (operand types are 'Test' and 'int')
//说明 5 还是个int类型, 不能隐式的转化为Test
}
explicit用于多个参数
#include <iostream>
struct P
{
P(int a, int b)
{
std::cout << "P(int a, int b)" << std::endl;
}
explicit P(int a, int b, int c)
{
std::cout << "explicit P(int a, int b, int c)" << std::endl;
}
};
int main()
{
P p1(1,2); //OK P(int a, int b)
P p2{1,2}; //OK P(int a, int b)
P p3 = {1,2}; //OK P(int a, int b)
P p4(1,2,3); //OK explicit P(int a, int b, int c)
P p5{1,2,3}; //OK explicit P(int a, int b, int c)
P p6 = {1,2,3}; //error:converting to 'P' from initializer list would use explicit constructor 'P::P(int, int, int)
}
标签:11,std,OK,cout,int,explict,explicit,C++,Test 来源: https://blog.csdn.net/pqbelieve/article/details/122768818