繁体   English   中英

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

[英]Making parent class members unmodifiable for each derived class

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

现在,我的代码正确地分配了其值(取决于调用父类的构造函数的Child类),但是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;
    }    
};

我的问题与有关,但继承似乎无法声明静态变量并通过成员初始化程序定义其值。

这个问题中,我已经找到了如何从Child类中调用父/基类构造函数。

提前致谢,

爱德华多


编辑

我对它做了一些修改,以免混淆任何人,因为const确实可以在我说不起作用的地方工作。

好吧,您没有陷入在没有成员初始化程序列表的情况下尝试使用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
    }    
};

防止派生类型修改其父级成员的唯一方法是将这些成员设为privateconst 由于您不能使成员const成为唯一方法,因此将成员声明为private并添加protected访问器方法,例如:

Piece_type get_type() const 
{
    return m_type;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM