T t2(t1) 等价于 T t2 = t1 么

 

Let's see the code:

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class T
{
public:
T(){}
~T(){}
T(const T &other)
{
cout <<"copy constructor" <<endl;
}
T &operator=(const T &other)
{
cout <<"operator=()" <<endl;
return *this;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
T t;

T t1(t);
T t2 = t;

return 0;
}

As we all know, 't1' and 't2' will call copy constructor to initialize the new object. But if I change the code as follow:

class T
{
public:
T(){}
~T(){}
explicit T(const T &other) // Here we add keyword 'explicit' to avoid implicit convertion.
{
cout <<"copy constructor" <<endl;
}
T &operator=(const T &other)
{
cout <<"operator=()" <<endl;
return *this;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
T t;

T t1(t); // Explicit convertion. Ok.
T t2 = t; // Implicit convertion. Compilation error!

return 0;
}


Now you can see that two statement are not equivalence in some way.

 

This knowledge comes from <<C++ 标准程序库>> p.18.

posted @ 2012-02-14 14:32  walfud  阅读(230)  评论(0编辑  收藏  举报