首页 > 代码库 > [C++] 变量、指针、引用作函数参数的区别

[C++] 变量、指针、引用作函数参数的区别


//============================================================================
// Name        : CppLab.cpp
// Author      : sodino
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <string>
using namespace std;

struct Student{
	string name;
};

int main() {
	void print(Student);
	void print_point(Student *);
	void print_reference(Student &);
	struct Student stu = {"Yao ming"};
	cout << "main &stu=" << &stu << endl << endl;

	print(stu);
	cout << "after print() name=" << stu.name << " no changed."<< endl << endl;

	print_point(&stu);
	cout << "after print_point() name=" << stu.name << " has been modified." << endl << endl;

	print_reference(stu);
	cout << "after print_reference() name=" << stu.name << " has been modified." << endl;
	return 0;
}

void print(Student stu) {
	// 实参转形参,会消耗额外的时间。print_reference()则效率高许多。
	cout << "print() stu address=" << &stu << " is different."<< endl; // 形参stu与函数体外的stu是两个不同的对象!!
	stu.name = "new.name"; // 这里的赋值并不会改变函数体外stu的name
	cout << "print() set new name=" << stu.name << endl;
}

void print_point(Student * stu) {
	stu->name = "new.point.name";
	cout << "print_point() set new name=" << stu->name << endl;
}

void print_reference(Student &stu) {
	stu.name = "new.reference.name";
	cout << "set new name=" << stu.name << endl;
}


main &stu=0x7fff5eabfbc8

print() stu address=0x7fff5eabfba0 is different.
print() set new name=new.name
after print() name=Yao ming no changed.

print_point() set new name=new.point.name
after print_point() name=new.point.name has been modified.

set new name=new.reference.name
after print_reference() name=new.reference.name has been modified.

print():用结构体变量作为实参和形参,简单明了,但在调用函数时形参要额外开辟内存,实参中全部内容通过值传递一一传给形参。造成空间和时间上的浪费。
print_point():指定亦是作为实参和形参,实参只是将stu的起始地址传给形参,而不是一一传递,也没有额外的内存开辟,效率高。但可读性可能不是很好。
print_reference():实参是结构体Student类型变量,而形参用该类型的引用,在执行函数期间,函数体操作的stu是函数体外的stu,可读性亦强。

C++中增设引用变量,提高效率的同时保持了高可读性。






[C++] 变量、指针、引用作函数参数的区别