【发布时间】:2012-01-01 23:52:12
【问题描述】:
我正在学习 C++ 中的面向对象编程。我对以下代码有一些疑问:
class Vehicle
{
protected:
string license ; int year ;
public:
Vehicle(const string &myLicense, const int myYear) : license(myLicense), year(myYear){}
const string getDesc() const
{
return license + " from " + stringify(year);
}
const string &getLicense() const {return license;}
const int getYear() const {return year;}
};
对函数的返回值使用引用运算符 (&) 是什么意思。为什么使用方便?我认为结果是完全一样的,无论你在getlicense函数中是否使用(&),你使用的内存量都是一样的。
为什么这段代码使用保留字 const?我看到它可以使用它。在代码中使用 const 有什么好处吗?
提前感谢您的帮助。
【问题讨论】: