Const方法 - 在实现中重复?

M.M*_*M.M 4 c++ methods const class

我一直在寻找答案而且找不到任何答案.说我有:

class foobar{
  public:
     char foo() const;
};
Run Code Online (Sandbox Code Playgroud)

,在我的foobar.h

当我想在foobar.cpp中实现这个类时,我应该重复一遍const吗?:

char foobar::foo() const{
//...my code
}
Run Code Online (Sandbox Code Playgroud)

或者我可以做(白色const)

char foobar::foo() {
//...my code
}
Run Code Online (Sandbox Code Playgroud)

如果这是重复的我很抱歉,但没有其他问题真正回答这个问题.

Bat*_*eba 5

您绝对必须const在实现中包含限定符.

可以根据其功能重载功能const.实际上,这是该语言的一个非常重要的部分.


Mat*_* F. 5

是的,您必须const在定义中包含限定符.如果你写:

class Foo
{
public:
    int f () const;
};
Run Code Online (Sandbox Code Playgroud)

在实现文件中,如果你写:

int Foo::f () { /*...*/ }
Run Code Online (Sandbox Code Playgroud)

那么编译器会发出一个错误int f (),说明类中没有带签名的函数.如果您将const关键字放在实现文件中,它也会起作用.

可以根据对象重载函数const.例:

class Foo
{
public:
    int foo ()       { std::cout << "non-const foo!" << std::endl; }
    int foo () const { std::cout << "const foo!" << std::endl; }
};

int main ()
{
    Foo f;
    const Foo cf;
    f.foo ();
    cf.foo ();
}
Run Code Online (Sandbox Code Playgroud)

输出将是(如预期的那样):

non-const foo!

const foo!

正如我们所做的那样const,您也可以根据对象重载函数volatile.