微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

给出这样的声明:
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关键字指示编译器接受对成员变量的修改,否则会导致编译器错误.当函数需要修改状态时使用,但是对象被认为在逻辑上是一致的(常数),而不管修改.

原文地址:https://www.jb51.cc/c/112299.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐