作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

#include
using namespace std;
class Test
{
public:
 Test()
 {
  ctor_count++;
  cout<<"ctor "<
 }
 Test(const Test & r)
 {
  ctor_count++;
  cout<<"copy ctor "<
 }
 Test & operator= (const Test& r)
 {
  ctor_count++;
  cout<<"assignment op "<
  return *this;
 }
private:
 static int ctor_count; //only a declaration
};
int Test::ctor_count=0; // definition + initialization
int main()
{
    Test test;
    Test test1=test;
    Test test2(test);
    Test test3=test2=test1;
    return 0;
}

运行结果为

[root@localhost ~]# ./a.out
ctor 1
copy ctor 2
copy ctor 3
assignment op 4
copy ctor 5

我们看到实例化test对象时调用了默认构造函数,test1使用了复制构造函数(因为这是一个新的对象产生),test2时也是用了复制构造函数,而test2=test1则使用了赋值构造函数(没有新的对象产生),test2=test3则使用了复制构造函数,原因同上。

 

所以要看是不是有新的对象产生,才能决定到底是调用了复制构造函数,还是赋值运算符。

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

相关文章:

  • 2022-01-06
  • 2021-06-03
  • 2021-07-04
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2022-02-01
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
相关资源
相似解决方案