When to use explicit keywork for class construct

来源:互联网 发布:bluehost php版本 编辑:程序博客网 时间:2024/06/08 05:52
/*
 * File:   main.cpp
 * Author: qzhao
 *
 * Created on 2011年7月2日, 上午8:12
 */

/*
 *  对构造函数,进行显示声明,是为了避免隐式转换,
 *
 */
#include <iostream>
#include <string>

using namespace std;

class A {
public:

    explicit A() : value(0) {
    }

private:
    int value;
};

void doSomething(const A& objA) {

}

class B {
public:

    explicit B(int a = 1, int b = 2) :
    m_a(a), m_b(b) {
    }

private:
    int m_a;
    int m_b;

};

void doSomething(const B& objB) {

}

class C {
public:

    explicit C(int c) :
    m_c(c) {
    }
private:
    int m_c;
};

void doSomething(const C& objC) {
}

/*
 *
 */
int main(int argc, char** argv) {

    A a;
    doSomething(a);

    B b(10);
    doSomething(b);

    doSomething(B(10));
    doSomething(C(10));

    return 0;
}
原创粉丝点击