如果传递对象的效率会低,因为要调用复制构造函数。
传递引用的话,执行效率会很高。
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; }
时间: 2024-10-27 07:51:31