曲径通幽论坛

标题: 只有一个参数的构造函数是如何隐式转换的? [打印本页]

作者: easy    时间: 2013-12-7 11:25
标题: 只有一个参数的构造函数是如何隐式转换的?
Q : 只有一个参数的构造函数是如何隐式转换的?

A : 只含有一个参数的构造函数,默认定义了一个隐式转换。比如下面的代码:

[C++] 纯文本查看 复制代码
#include "stdafx.h"
#include <iostream>
using namespace std;


class myclass {
    int a;
public:
    myclass(int x) { a = x; }
    int geta() { return a; }
};


int _tmain(int argc, _TCHAR* argv[])
{
    myclass ob1(4);


    cout << ob1.geta() << endl;


    myclass ob2 = 5;    //隐式构造


    cout << ob2.geta() << endl;


    return 0;
}

在声明 ob2 这个对象时,使用的是隐式构造方式。输出结果为:
4
5

如果将 myclass ob2 = 5; 改成 myclass ob2 = 'a'; ,那么输出结果为:
4
97

字符 'a' 的 ASCII 码十进制为 97 。也就是说,原本上只是希望隐式对 int 型进行转换,但是这里对 char 型也进行了隐式转换,在有些情况下,这会造成迷惑与误解。隐式转换通常不是好主意,阻止这一做法就是使用 explicit 关键字。





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2