在C++中,(void)在参数中做了什么?

Tan*_*iel 0 c++ methods void

我有一行代码如下:

int method(void) const;
Run Code Online (Sandbox Code Playgroud)

但是我不确定参数中的(void)是什么,或者const是什么.这也应该是一个公共'get',我不确定如何在类中接近(void)和const.

Cor*_*mer 5

它没有做任何事情.它是来自C的结转,表示(在C++中)该函数不带参数.以下签名是等效的

int method() const;
Run Code Online (Sandbox Code Playgroud)

const函数的下列名称表示(因为这意味着该函数是一个类方法)的功能是不允许改变任何类实例的成员变量的.

要实现"setter"和"getter",你通常会有这样的东西

class Foo()
{
public:
    int GetX() const  { return x; }   // getter method
    void SetX(int x_) { x = x_; }     // setter method
private:
    int x;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们可以声明getter,const因为它不会修改值x,但是setter不能,const因为该方法的整个目的是为其分配一个新值x.