[C++] 變量、指針、引用作函數(shù)參數(shù)的區(qū)別
來(lái)源:程序員人生 發(fā)布時(shí)間:2014-12-12 08:03:44 閱讀次數(shù):3304次
//============================================================================
// 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) {
// 實(shí)參轉(zhuǎn)形參,會(huì)消耗額外的時(shí)間。print_reference()則效力高許多。
cout << "print() stu address=" << &stu << " is different."<< endl; // 形參stu與函數(shù)體外的stu是兩個(gè)不同的對(duì)象!!
stu.name = "new.name"; // 這里的賦值其實(shí)不會(huì)改變函數(shù)體外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():用結(jié)構(gòu)體變量作為實(shí)參和形參,簡(jiǎn)單明了,但在調(diào)用函數(shù)時(shí)
形參要額外開辟內(nèi)存,實(shí)參中全部?jī)?nèi)容通過(guò)值傳遞逐一傳給形參。造成空間和時(shí)間上的浪費(fèi)。
print_point():指定亦是作為實(shí)參和形參,實(shí)參只是將stu的起始地址傳給形參,而不是逐一傳遞,也沒有額外的內(nèi)存開辟,效力高。但可讀性可能不是很好。
print_reference():實(shí)參是結(jié)構(gòu)體Student類型變量,而形參用該類型的援用,在履行函數(shù)期間,函數(shù)體操作的stu是函數(shù)體外的stu,可讀性亦強(qiáng)。
C++中增設(shè)援用變量,提高效力的同時(shí)保持了高可讀性。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)