C++ 使每个派生类的父类成员不可修改

C++ 使每个派生类的父类成员不可修改,c++,c++11,inheritance,constructor,C++,C++11,Inheritance,Constructor,我想知道如何使不可修改的父类成员对于每个派生类都是不同的 我的代码现在正确地分配了它的值(取决于调用父类构造函数的子类),但是m_type可以很容易地修改(例如在myfunction中),这就是我想要避免的 #include <iostream> enum Piece_type{ king=1, queen=3, rook=3, bishop=4, knight=5, pawn=6}; class Piece { protected:

我想知道如何使不可修改的父类成员对于每个派生类都是不同的

我的代码现在正确地分配了它的值(取决于调用父类构造函数的子类),但是
m_type
可以很容易地修改(例如在
myfunction
中),这就是我想要避免的

#include <iostream>

enum Piece_type{    king=1,     queen=3,    rook=3,     bishop=4,   knight=5,   pawn=6};

class Piece
{
    protected:
        Piece_type  m_type; // static Piece_type m_type; <- doesn't work

        Piece(Piece_type ex): m_type(ex) {}
};

class Pawn: public Piece
{
public:
    Pawn():Piece(pawn) {}   // To initialise m_type as pawn for all my Pawn objects

    void myfunction()
    {
        std::cout<<"My piece type is "<< m_type<<std::endl;;
        m_type= knight;   // This is the assignation I want to avoid happening
        std::cout<<"My new piece type i "<<m_type<<std::endl;
    }    
};
#包括
枚举块_类型{国王=1,王后=3,车=3,主教=4,骑士=5,兵=6};
班级作品
{
受保护的:

Piece_-type m_-type;//静态Piece_-type m_-type;好吧,您没有陷入通常的错误,即在没有成员初始值设定项列表的情况下尝试使用
const
成员变量,因此
const
是您真正需要的:

class Piece
{
protected:
    Piece_type const m_type;

    Piece(Piece_type ex) : m_type(ex) { }
};

class Pawn : public Piece
{
public:
    Pawn() : Piece(pawn) { }

    void myfunction()
    {
        // m_type = knight; // Compile-time error
    }    
};

好吧,您没有陷入通常的错误,即尝试在没有成员初始值设定项列表的情况下使用
const
成员变量,因此
const
才是您真正需要的:

class Piece
{
protected:
    Piece_type const m_type;

    Piece(Piece_type ex) : m_type(ex) { }
};

class Pawn : public Piece
{
public:
    Pawn() : Piece(pawn) { }

    void myfunction()
    {
        // m_type = knight; // Compile-time error
    }    
};

防止派生类型修改其父级成员的唯一方法是将这些成员设置为私有的
private
const

Piece_type get_type() const 
{
    return m_type;
}

这样,派生类就可以调用
get_type()
要知道
m_type
的值,但不能直接访问它,从而阻止它们写入该值。

防止派生类型修改其父级成员的唯一方法是使这些成员
私有
常量
。因为不能使成员
常量
,所以唯一的其他方法是decl成员
是私有的
并且添加了一个
受保护的
访问器方法,例如:

Piece_type get_type() const 
{
    return m_type;
}

通过这种方式,派生类可以调用
get_type()
来了解
m_type
的值,但不能直接访问它,从而阻止它们对其进行写入。

static
与“不可修改”无关。为什么不能生成
m_-type
const
?为什么试图通过
m_-type
成员和
Pawn
类来表示工件类型?为什么两者都需要?@user2357112“错误:只读成员'piece::m_-type'的赋值”我必须承认,我对你的第二个问题没有答案。@Eduardo:这个错误正是你所要求的。如果你不想在试图修改你想要的不可修改的东西时出错,你想要什么?
static
与“不可修改”无关。为什么不能生成
m_-type
const
?为什么试图通过
m_-type
成员和
Pawn
类来表示工件类型?为什么两者都需要?@user2357112“错误:只读成员'piece::m_-type'的赋值”我必须承认,我对你的第二个问题没有答案。@Eduardo:这个错误正是你所要求的。如果你不想在试图修改你想要的不可修改的东西时出错,你想要什么?看起来
const
终于起作用了,但无论如何,谢谢你,我会考虑的!看起来
const
终于奏效了,不过还是要谢谢你,我会考虑的!