[C++] 变量、指针、引用作函数参数的区别
来源:程序员人生 发布时间:2014-12-12 08:03:44 阅读次数:3112次
//============================================================================
// 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++中增设援用变量,提高效力的同时保持了高可读性。
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠