C++:编写自己的函数时要keep in mind

本文探讨了C++中返回引用的限制条件及其原因,同时讨论了从派生类中使用基类成员的重要原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2014.2

函数的返回类型可以是reference to an object,例如:

// return a reference to the shorter of two strings(C++ primer 5th edition)

const string &shorterString( const string &s1, const string &s2)

{

  return s1.size() <= s2.size() ? s1:s2;

}


但是不能返回reference或者pointer to a “local” object

原因是“After a function terminates, references to local objects refer to memory that is no longer valid.”


以上是两部分原理。


思考:最后看到一面那段程序,parameter list中两个parameter都是pass by reference。

函数返回类型是reference to an object,如果将两个parameter的“&”去掉,就使得paramter变为pass by value,那么以此方式传入的argument就是只在函数里面存在的一个argument,函数结束时会被destroyed,所以改动后的程序应该是错的,并且其错误原因应该就是返回了local object的引用。

经过验证,以下这段程序确实如预料的。

//  intend to return a reference to the shorter of two strings, but may be erroneous

const string &shorterString( const string s1, const string s2)

{

  return s1.size() <= s2.size() ? s1:s2;

}



2014.4

C++ primer 5th edition

15.2 "Using Members of the Base Class from the Derived Class"

重要观点“Interactions with an object of a class-type should use the interface of that class, even if that object is the base-class part of a derived object.”

"Declarations of Derived Classes"

重要观点"The purpose  of a declaration is to make known that a name exists and what kind of entity it  denotes, for example, a class, function, or variable."

So, declaration with inheritance list like:"class Bulk_quote: public Quote;" is wrong, "class Bulk_quote" is right.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值