【问题标题】:Const in class method [duplicate]类方法中的常量 [重复]
【发布时间】:2020-08-13 22:22:09
【问题描述】:

在这段代码中,我不确定关键字“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;
};

【问题讨论】:

  • 是的,你是对的。我认为“方法前的 const”是指返回类型的一部分

标签: c++ class methods constants


【解决方案1】:

假设您手头没有Date 对象,而只有一个对其的常量引用,const Date&。您只能在该引用上调用 const 方法。这些方法通过它们的签名保证它们不会改变Date 对象(并且编译器也不会允许它)。 mutable 成员是一个例外。

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

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2013-04-04
    • 2021-08-30
    • 2013-11-19
    • 2013-08-23
    • 1970-01-01
    • 2017-04-20
    • 2020-12-20
    • 2013-05-17
    相关资源
    最近更新 更多