在 class 内更改 const 成员

Changing const member within class

我想让 const int 由 class 中的函数更改。

class Parent 
{
int currentIndex; 
private: 
    initMember(const int& member) 
    {
        member = currentIndex++;
    }

}


class Child 
{
const int Member1;
const int Member2;

    Child () 
    {
        initMember(Member1);
        initMember(Member2);
    }



}

编写子class 的人应该只声明const int 用于索引。实际值应由 Parent 管理,因为此 class 使用该值来处理数组中的内容等。所以目标是让subclass的writer声明,而不是改变(至少不容易)Member1Member2.

最好的方法是什么?

您可能正在寻找一种在创建时使用父级中的数据成员来初始化 const 成员的方法 class:

class Parent 
{
    protected:
    int currentIndex; 
};

class Child : public Parent
{
   const int Member1;
   const int Member2;

    Child () : Member1(currentIndex++), Member2(currentIndex++)
    {
    }
};

非静态常量成员必须在成员初始化器列表中初始化,之后不能更改。 你可以试试这个:

class Child
{
private:
    int _currentIndex;
    const int _member1, _member2;
public:
    Child() :
        _currentIndex(0),
        _member1(_currentIndex++),
        _member2(_currentIndex++)
    {
    }
};