显式和隐式构造函数
explicit & implicit constructors
本文关键字:构造函数 更新时间:2023-10-16
我已经在stackoverflow上阅读了许多关于隐式和显式构造函数的问题,但是我仍然无法区分隐式和显式构造函数。
我想知道是否有人可以给我一个很好的定义和一些例子,或者可能指导我去解释这个概念的书/资源
以以下为例:
class complexNumbers {
double real, img;
public:
complexNumbers() : real(0), img(0) { }
complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
complexNumbers( double r, double i = 0.0) { real = r; img = i; }
friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
cout<<"Real Part: "<<cx.real<<" Imag Part: "<<cx.img<<endl;
}
int main() {
complexNumbers one(1);
display(one);
display(300); //This code compiles just fine and produces the ouput Real Part: 300 Imag Part: 0
return 0;
}
由于方法display
需要类complexNumbers
的对象/实例作为参数,因此当我们传递一个十进制值300时,将在适当的位置进行隐式转换。
为了克服这种情况,我们必须强制编译器只使用显式构造创建对象,如下所示:
explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; } //By Using explicit keyword, we force the compiler to not to do any implicit conversion.
并且在这个constructor
出现在您的类之后,语句display(300);
将给出一个错误
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为