C++对象的常引用

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.reset(t1);

t1.Print();

return 0;

}

输出结果:

12/12/12

12/12/12

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;

}

输出结果:

12/12/12

0/0/0

3形参为对象的常引用

在函数中只能使用对象t中的数据成员和成员函数,而不能修改其中的成员函数,也就是不能修改其对应的参数中的数据成员的值。

上面的代码可以改成:

#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(const 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;

}

输出结果:

12/12/12

12/12/12

既然声明了t是对象的常引用,就不可以修改其数据成员的值

 

原文链接: https://www.cnblogs.com/DannyShi/p/4584519.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++对象的常引用

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/217804

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午9:56
下一篇 2023年2月13日 上午9:57

相关推荐