构造函数或赋值运算符 [英] Constructor or Assignment Operator

查看:129
本文介绍了构造函数或赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能帮助我是C ++标准中的定义,描述了在这种情况下,哪一个将被称为构造函数或赋值运算符:

Can you help me is there definition in C++ standard that describes which one will be called constructor or assignment operator in this case:

#include <iostream>

using namespace std;

class CTest
{
public:

 CTest() : m_nTest(0)
 {
  cout << "Default constructor" << endl;
 }

 CTest(int a) : m_nTest(a)
 {
  cout << "Int constructor" << endl;
 }

 CTest(const CTest& obj)
 {
  m_nTest = obj.m_nTest;
  cout << "Copy constructor" << endl;
 }

 CTest& operator=(int rhs)
 {
  m_nTest = rhs;
  cout << "Assignment" << endl;
  return *this;
 }

protected:
 int m_nTest;
};

int _tmain(int argc, _TCHAR* argv[])
{
 CTest b = 5;

 return 0;
}

还是只是编译器优化的问题?

Or is it just a matter of compiler optimization?

推荐答案

这里发生的情况取决于你的编译器。它可以使用int构造函数创建一个临时对象,然后从该临时对象中复制构造函数b。它很可能会删除复制构造函数调用。在这两种情况下都不会使用赋值运算符。

What is happening here depends a bit on your compiler. It could create a temporary object using the int constructor and then copy construct b from that temporary. It will most likely elide the copy constructor call however. In neither case will the assignment operator be used.

这篇关于构造函数或赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆