【C++对象模型】函数返回C++对象的问题

在深入C++对象模型中,对于形如

CObj obj1 = Get(obj2);

的形式,编译器会在将其改变为如下

Get(obj, CObj&  obj1);

将赋值操作符左边的变量作为函数的一个引用参赛,在函数内部改变其值;

 

如下

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

class CTest
{
public:
    CTest(int a, int b);
    virtual ~CTest();
    CTest(const CTest& obj);
    CTest& operator=(const CTest& obj);

protected:
    int m_nValue1;
    int m_nValue2;
};

CTest::CTest(int a, int b) : m_nValue1(a), m_nValue2(b){cout << "构造函数被调用\r\n";}
CTest::~CTest(){}
CTest::CTest(const CTest& obj)
{
    cout << "拷贝构造函数被调用\r\n";
    this->m_nValue1 = obj.m_nValue1;
    this->m_nValue2 = obj.m_nValue2;
}

CTest& CTest::operator=(const CTest& obj)
{
    cout << "重载赋值运算符\r\n";
    this->m_nValue1 = obj.m_nValue1;
    this->m_nValue2 = obj.m_nValue2;

    return *this;
}

 

返回类对象的函数

CTest get(CTest obj)
{
    CTest objTemp = obj;

    return objTemp;    
}

 

main函数及执行结果

int _tmain(int argc, _TCHAR* argv[])
{
    CTest obj(10, 20);
    
    CTest obj2 = get(obj);

    return 0;
}

 

 

上述代码,构造函数被调用一次,拷贝构造被调用三次,重载的赋值运算符没有被调用;

 

调用时机:

构造函数:

CTest obj(10, 20);

 

拷贝构造函数:

①调用get函数时,将实参传递给get函数时,需要调用拷贝构造函数拷贝一个实参obj的副本

②get函数内部, CTest objTemp = obj;

③函数返回之前,将objTemp的作为拷贝构造的参数拷贝构造obj2;

 

所以,get函数被改编为如下

 

CTest obj2;  //不执行其构造函数

void get(CTest obj/*obj参数不变*/,   CTest& __result /*附加参数*/)
{
    //处理obj

  __result.CTest::CTest(obj2) //拷贝构造 

    return; //不返回任何值 
 }

 

 

 

 

所以,当函数的返回值为类对象时,要注意其构造函数的编写。

 

 

 

posted on 2014-05-19 23:42  崔好好  阅读(286)  评论(1编辑  收藏  举报

导航