加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 20:22:26 所属栏目:PHP教程 来源:网络整理
导读://============================================================================// Name : CppLab.cpp// Author : sodino// Version :// Copyright : Your copyright notice// Description : Hello World in C++,Ansi-style//===========================


//============================================================================ // 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++中增设援用变量,提高效力的同时保持了高可读性。






(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读