这是一篇关于关于explicit修饰符的使用问题。
1.explicit修饰构造函数
explicit修饰类的构造函数,指定构造函数或转换构造函数为显示,不能进行自动隐式类型转换和复制初始化
1.1转换构造函数
不以说明符explicit修饰的且为单参数的构造函数,称之为转换构造函数,因其总是可以进行自动类型转换而得名
````c++
#include <iostream>
class twoNumber {
public:
twoNumber(int x, int y = 5)
:oneNumber(x), anotherNumber(y) {
//std::cout << "twoNumber" << std::endl;
}
twoNumber operator+(const twoNumber& other) {
return twoNumber(this->oneNumber + other.oneNumber,this->anotherNumber+other.anotherNumber);
}
void getNumber() {
std::cout << "oneNumber is " << oneNumber << "anotherNumber is " << anotherNumber << std::endl;
}
private:
int oneNumber;
int anotherNumber;
};
class twoNumberWithExplicit {
public:
explicit twoNumberWithExplicit(int x, int y = 5) :oneNumber(x), anotherNumber(y) {
//std::cout << "twoNumber" << std::endl;
}
twoNumberWithExplicit operator+(const twoNumberWithExplicit& other) {
return twoNumberWithExplicit(this->oneNumber + other.oneNumber, this->anotherNumber + other.anotherNumber);
}
void getNumber() {
std::cout << "oneNumber is " << oneNumber << "anotherNumber is " << anotherNumber << std::endl;
}
private:
int oneNumber;
int anotherNumber;
};
int main() {
//使用explicit修饰的构造函数
twoNumber a(5,3);
twoNumber X = a + 6; //进行隐式类型转换,将6转换为 twoNumber(6,5)
X.getNumber();
//不使用explicit修饰的构造函数
twoNumberWithExplicit b(5);
//twoNumberWithExplicit Y = b + 3; //没有与这些操作数匹配的+运算符
system("pause");
return 0;
}
> \- [注意] **与explicit相对的,还有一个implicit修饰符,但是这不是c++的修饰符,是c#等语言的修饰符,implicit明确指定可以进行隐式类型转换**