explicit Constructors——显式构造函数

本文探讨了C++中explicit构造函数的作用,解释了当一个类具有单参数构造函数时,如何防止编译器自动进行隐式类型转换。通过示例代码展示了不使用和使用explicit关键字时的区别,强调了在不期望类型转换发生时应使用explicit关键字来避免潜在错误。
摘要由CSDN通过智能技术生成

首先引用一段《ANSI/ISO C++Professional Programmer'sHandbook》中的解释:

explicit Constructors
A constructor that takes a single argument is, by default, an implicit conversion operator, which converts its argument to an object of its class (see also Chapter 3, "Operator Overloading"). Examine the following concrete example:

class string
{
private:
    int size;
    int capacity;
    char *buff;
public:
    string();
    string(int size); // constructor and implicit conversion operator
    string(const char *); // constructor and implicit conversion operator
    ~string();
};


Class string has three constructors: a default constructor, a constructor that takes int, and a constructor that constructs a string from const char *. The second constructor is used to create an empty string object with an initial preallocated buffer at the specified size. However, in the case of class string, the automatic conversion is dubious. Converting an int into a string object doesn't make sense, although this is exactly what this constructor does.
Consider the following:

int main()
{
     string s = "hello"; //OK, convert a C-string into a string object
     int ns = 0;
     s = 1; // 1 oops, programmer intended to write ns = 1,
}

In the expression s= 1;, the programmer simply mistyped the name of the variable ns, typing s instead. Normally, the

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值