加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中使用方法时,const运算符意味着什么?

发布时间:2020-12-16 03:11:13 所属栏目:百科 来源:网络整理
导读:给出这样的声明: class A {public: void Foo() const;}; 这是什么意思? Google表示: Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const,in
给出这样的声明:
class A {
public:
    void Foo() const;
};

这是什么意思?

Google表示:

Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const,in can not be applied to a const object,and the compiler will give an error message.

但我觉得有点混乱有谁能在更好的条件吗?

谢谢.

解决方法

考虑你的班级A的变化.
class A {
public:
    void Foo() const;
    void Moo();

private:
    int m_nState; // Could add mutable keyword if desired
    int GetState() const   { return m_nState; }
    void SetState(int val) { m_nState = val; }
};

const A *A1 = new A();
A *A2 = new A();

A1->Foo(); // OK
A2->Foo(); // OK

A1->Moo(); // Error - Not allowed to call non-const function on const object instance
A2->Moo(); // OK

函数声明中的const关键字向编译器指示该函数是合约义务不修改A的状态.因此,您无法调用A :: Foo中的非const函数,也不能更改成员变量的值.

为了说明,Foo()可能不会调用A :: SetState,因为它被声明为非const,A :: GetState是可以的,因为它被明确声明为const.除非用关键字mutable声明,否则成员m_nState可能不会被更改.

const的这个用法的一个例子是“getter”函数来获取成员变量的值.

@1800 Information: I forgot about mutable!

mutable关键字指示编译器接受对成员变量的修改,否则会导致编译器错误.当函数需要修改状态时使用,但是对象被认为在逻辑上是一致的(常数),而不管修改.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读