直接傳遞對象名
用對象名做函數參數時,在函數調用時將建立一個新的對象,它是形參對象的拷貝。
================下面給出一個直接傳遞對象名的例子程序1.1==================
#include<iostream>
using namespace std;
class Time
{
public:
Time(int,int,int);//構造函數
void Print();//輸出信息函數
void reset(Time t);//重置函數
private:
int year;
int month;
int day;
};
Time::Time(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void Time::Print()
{
cout<<year<<"/"<<month<<"/"<<day<<endl;
}
void Time::reset(Time t)
{
t.year=0;
t.month=0;
t.day=0;
}
int main()
{
Time t1(12,12,12);//定義一個對象并初始化
t1.Print();//輸出t1的數據成員
t1.reset(t1);//重置t1中的數據成員
t1.Print();//輸出t1中的數據成員
return 0;
}
運行結果:
從運行結果來看,reset函數并沒有起到作用。
實參把值傳遞給形參,二者分別占不同的存儲空間。無論形參是否修改都不會到實參的值。這種形式的虛實結合,要產生實參的拷貝,當對象的規模比較大的時候,則時間開銷和空間開銷都可能很大。
因此,這種方法雖然可行,但是并不提倡這種用法~
形參為對象的引用
如果形參為對象的引用名,實參為對象名,則在調用函數進行虛實結合時,并不是為形參另外開辟一個存儲空間(常稱為建立實參的一個拷貝),而是把實參變量的地址傳給形參(引用名),這樣引用名也指向實參變量。
對于程序1.1而言,我們只需要將reset函數的形參聲明為對象的引用即可。
#include<iostream>
using namespace std;
class Time
{
public:
Time(int,int,int);//構造函數
void Print();//輸出信息函數
void reset(Time &t);//重置函數 ============對這一行代碼進行了修改======================
private:
int year;
int month;
int day;
};
Time::Time(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void Time::Print()
{
cout<<year<<"/"<<month<<"/"<<day<<endl;
}
void Time::reset(Time &t)//==============對這一行代碼進行了修改=================
{
t.year=0;
t.month=0;
t.day=0;
}
int main()
{
Time t1(12,12,12);
t1.Print();
t1.reset(t1);
t1.Print();
return 0;
}
運行結果:
形參為對象的常引用
如果我們在聲明函數的參數為對象引用的時候,還可以將它聲明為const(常引用)
void reset(const Time &t);
則在函數中只能使用對象t中的數據成員和成員函數,而不能修改其中的成員函數,也就是不能修改其對應的實參中的數據成員的值。
#include<iostream>
using namespace std;
class Time
{
public:
Time(int,int,int);//構造函數
void Print();//輸出信息函數
void reset(const Time &t);//重置函數
private:
int year;
int month;
int day;
};
Time::Time(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void Time::Print()
{
cout<<year<<"/"<<month<<"/"<<day<<endl;
}
void Time::reset(const Time &t)
{ //既然聲明了t是對象的常引用,就不可以修改其數據成員的值,因此,下面的三行代碼是錯誤的。。
t.year=0;
t.month=0;
t.day=0;
}
int main()
{
Time t1(12,12,12);
t1.Print();
t1.reset(t1);
t1.Print();
return 0;
}
該程序會報錯,因為在函數reset中,企圖修改對象t中的數據成員的值