码迷,mamicode.com
首页 > 其他好文 > 详细

传递的时候尽量传引用

时间:2016-03-19 15:56:15      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

如果传递对象的效率会低,因为要调用复制构造函数。

传递引用的话,执行效率会很高。

main.cpp

#include <iostream>
#include "TestClass.h"
using namespace std;
TestClass test(){
    TestClass t;
    return t;
}
void test1(TestClass testClass){
    cout << "对象作为参数传递" << endl;
}
void test2(TestClass &testClass){
    cout << "引用作为参数传递" << endl;
    cout << "最好传引用" << endl;
    cout << "如果担心值被改变,那就加上const,有成员函数是用不了,就把要调用的函数加上const" << endl;
}
int main(){
    TestClass t1 = test();
    cout << "开始调用" << endl;
    test1(t1);
    test2(t1);
    system("pause");
    return 0;
}

 

TestClass.h

#pragma once
class TestClass
{
public:
    TestClass();
    TestClass(const TestClass &testClass);
    ~TestClass();
};

TestClass.cpp

#include "TestClass.h"
#include <iostream>
using namespace std;
TestClass::TestClass()
{
    cout << "testClass" << endl;
}
TestClass::TestClass(const TestClass &testClass){
    cout << "copy constructor" << endl;
}
TestClass::~TestClass()
{
    cout << "destructor" << endl;
}

 

传递的时候尽量传引用

标签:

原文地址:http://www.cnblogs.com/letben/p/5295138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!