C++具有虚函数的导数类

C++ derivative class with virtual function

本文关键字:函数 C++      更新时间:2023-10-16

我在某些任务上遇到了问题。我需要编写一个派生类,其中我需要确定向量 FVect 仅包含字符<'a';"z">。

class Something {
private:
   char FVect[3];
protected:
   virtual void setValue(int _idx, char _val) { FVect[_idx] = _val; }
public:
   Something() {};
};

我不知道如何在派生类中编写方法(无需在类 Something 中进行更改(,因为 FVect 是私有的。

感谢您的帮助。

使用当前的设置,您唯一能做的是在从Something派生的类中实现setValue(),并在_val超出有效值时引发异常,否则如果基类方法有效,则调用基类方法:

class Derived : public Something {
    ...
    void setValue(int _idx, char _val) {
        if ((_val < 'a') || (_val > 'z')) throw std::invalid_argument( "invalid character" );
        Something::setValue(_idx, _val);
    }
    ...
};