在c ++中的括号之前添加const

one*_*day 3 c++ oop

只是想知道为什么虚函数的语法在花括号之前使用const,如下所示:

  virtual void print(int chw, int dus) const;
Run Code Online (Sandbox Code Playgroud)

顺便说一句,代码似乎没有const,这很有趣..不知道为什么?

非常感谢!

Geo*_*che 8

const在函数签名标志着一个const成员函数 -安东尼·威廉姆斯给予了极大的答案上的影响.
请注意,在这方面虚拟成员函数函数没有什么特别之处,constness是一个适用于所有非静态成员函数的概念.

至于为什么它没有工作 - 你不能在const实例上调用非const成员.例如:

class C {
public:
  void f1() {}
  void f2() const {}
};

void test() 
{
    const C c;
    c.f1(); // not allowed
    c.f2(); // allowed
}
Run Code Online (Sandbox Code Playgroud)