C++:编译时和运行时不允许派生类中的虚拟函数
C++: disallowing virtual function in derived class at compile vs runtime
我有一个具有方法void setup(const int* p)
的父class RO
。我需要一个子class RW
有相同的方法,只允许非常量指针。
我通过在class RO
中创建两个方法并在class RW
:中禁用其中一个方法来实现这一点
class RO
{
public:
void setup(int* p) { DO SMTH }
virtual void setup (const int* p) { RO::setup( const_cast<int*>(p) ); }
// the rest...
void read() const;
};
class RW : public RO
{
public:
virtual void setup (const int* p) { throw SMTH }
// the rest...
void write();
};
如果可能的话,我希望能够在编译时禁止RW::setup
。即
const int* p;
RO* ro = new RW;
ro->setup(p); // Throw at run time, since it can be unknown
// at compile time that ro points to RW and not to RO.
RW* rw = new RW;
rw->f(p); // Disallow this at compile time, since it is
// known at compile time that rw points to RW.
有办法做到吗?
使用私有继承而不是公共继承。使用using
关键字使父类的方法在子类中可用。
公共继承适用于使用父类对象的人也可以使用chid类对象的情况(有关详细信息,请查阅Liskov替换原则)。您的要求打破了这一点,因此不存在公共继承的情况。
听起来class RO
有一个不变量:"永远不要修改*p
"(即使它在p
上偷偷地修改了const_cast
)。如果class RW
违反了这个不变量,它就不能是class RO
的子类。
我猜你真正想要的是更像的东西
class Readable {
public:
virtual ~Readable();
virtual void read() const = 0;
};
class RO
: public Readable {
public:
void setup(const int* p);
void read() const;
private:
const int* m_p;
};
class RW
: public Readable
{
public:
void setup(int* p);
void read() const;
void write();
private:
int* m_p;
};
如果接下来的问题是:"DRY呢?现在我必须实现两次read()
?",请注意,您可以在基类Readable
中定义一个静态成员函数,类似于:
static void do_read(const int* p);
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 用纯虚拟函数兜圈子
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 无法在子类中使用虚拟函数C++
- 无法在派生对象上运行虚拟函数
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 在 C++ 中将函数获取和设置为虚拟函数
- 使用在堆栈上创建的对象调用虚拟函数
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在C++中使虚拟函数私有化
- 模板继承类中的虚拟函数
- 为什么构造函数的虚拟函数调用有时有效,但其他调用却无效
- doxygenc++虚拟函数和实现
- 如何从派生类函数中调用虚拟函数