【c++】【转】c++中的explicit关键字

http://www.cnblogs.com/chio/archive/2007/09/17/895263.html

c++中的explicit关键字用来修饰类的构造函数,表明该构造函数是显式(调用)的,既然有"显式"那么必然就有"隐式",那么什么是显示而什么又是隐式的呢?

如果c++类的构造函数有一个参数,那么在编译的时候就会有一个缺省的转换操作:将该构造函数参数对应数据类型的数据转换为该类对象,如下面所示:

class MyClass
{
public:
     MyClass(int num){};
};

MyClass obj = 10;//10被隐式调用构造函数转换为MyClass类型对象

在上面的代码中编译器自动将整型转换为MyClass类对象,实际上等同于下面的操作:
MyClass temp(10);
MyClass obj = temp;
上面的所有的操作即是所谓的"隐式转换"。

如果要避免这种自动转换的功能,我们该怎么做呢?这就是关键字explicit的作用了,将类的构造函数声明为"显式",也就是在声明构造函数的时候前面添加上explicit即可,这样就可以防止这种自动的转换操作,如果我们修改上面的MyClass类的构造函数为显式的,那么下面的代码就不能够编译通过了,如下所示:

class MyClass
{
public:
     explicit MyClass(int num){};
};

MyClass obj = 10;//出错

class Rational
{
public:
    Rational(int numerator = 0, int denominator = 1)
    {
        this->numerator = numerator;
        this->denominator = denominator;
    }
    ~Rational(){}
    int get_numerator()
    {
        return numerator;
    }
    int get_denominator()
    {
        return denominator;
    }

    const Rational operator*(const Rational &rhs) const;

private:
    int numerator;
    int denominator;
};

const Rational Rational::operator*(const Rational &rhs) const
{
    return Rational(numerator * rhs.numerator, denominator*rhs.denominator);
}

int main()
{
    Rational a(2, 1);
    //Rational b = 2 * a;//编译出错,相当于2.operator*(a),而2不是Rational类型
    Rational b = a * 2;//2会被隐式类型转换为Rational对象
    cout << b.get_numerator() << " " << b.get_denominator() << endl;

    system("pause");
    return 0;
}

上述有理数运算不满足交换律,所以需要改进

class Rational
{
public:
    Rational(int numerator = 0, int denominator = 1)
    {
        this->numerator = numerator;
        this->denominator = denominator;
    }
    ~Rational(){}
    int get_numerator() const
    {
        return numerator;
    }
    int get_denominator() const
    {
        return denominator;
    }

private:
    int numerator;
    int denominator;
};

const Rational operator*(const Rational& lhs,const Rational &rhs) 
{
    return Rational(lhs.get_numerator() * rhs.get_numerator(), lhs.get_denominator()*rhs.get_denominator());
}

int main()
{
    Rational a(2, 1);
    //2会被隐式类型转换为Rational对象
    Rational b = 2 * a;
    //Rational b = a * 2;
    cout << b.get_numerator() << " " << b.get_denominator() << endl;

    system("pause");
    return 0;
}

总结:如果你需要为某个函数的所有参数进行类型转换,那么这个函数必须是个non-member(effective c++ 条款24)

绝不要返回指针或引用指向一个local stack对象,因为local stack对象当退出函数时就被析构了,也就是说指针或者引用指向未知的内存;不要返回引用指向一个heap-allocated对象,会导致内存泄漏;不要返回指针或引用指向一个local static对象,因为有可能同时需要多个这样的对象,此时这些对象其实都是同一个对象。所以一个必须返回新对象的函数的正确写法是:让那个函数返回一个新对象,不用担心拷贝构造函数导致的性能损失。例子可见上面的operator*的写法(effective c++ 条款21)

原文地址:https://www.cnblogs.com/ljygoodgoodstudydaydayup/p/3897349.html