Const in class method [duplicate]

问题描述 投票:0回答:1
在这段代码中,我不确定关键字“ const”在做什么。我的猜测是这使得无法更改该类的私有变量,但是我不确定。尽管如此,我无法理解方法前面或后面的“ const”的区别。还是同一回事?

class Date { public: Date(unsigned int y, unsigned int m, unsigned int d); Date(string yearMonthDay); // yearMonthDay must be in format "yyyy/mm/dd" void setYear(unsigned int y); void setMonth(unsigned int m); void setDay(unsigned int d); void setDate(unsigned int y, unsigned int m, unsigned int d); unsigned int getYear() const; unsigned int getMonth() const; unsigned int getDay() const; string getDate() const; // returns the date in format "yyyy/mm/dd" void show() const; // shows the date on the screen in format "yyyy/mm/dd" private: unsigned int year; unsigned int month; unsigned int day; };

c++ class methods const
1个回答
0
投票
假设您手头没有Date对象,但只有一个const引用,即const Date&。仅允许您在该引用上调用const方法。这些方法以其签名保证不会更改Date对象(并且编译器也不允许这样做)。 mutable成员是一个例外。签名前面的

A const关键字与return参数有关。因此,例如,const std::string& getName() const;返回对字符串的const引用。它本身就是const,因为它不会更改对象。这是签名前后的const的两种含义。

© www.soinside.com 2019 - 2024. All rights reserved.