我有
class Rect{
// stuff
};
和
class SpecialRect:public Rect{
private:
operator const Rect(){return *this;} // No implicits casts to Rect
public:
// stuff
};
SpecialRect 继承了 Rect 的所有属性和方法,除了我想避免从 SpecialRect 到基类 Rect 的非显式转换。
在代码中
SpecialRect oneSpecial;
Rect aRect=oneSpecial; // I want this to not compile. (to remind-me to declare aRect as SpecialTect)
编译没有错误。 (我知道将基类 Rect 声明为私有(private)就可以了,但我不想重新实现它的所有方法。)
有什么办法可以实现吗?
最佳答案
在 Rect 中声明 SpecialRect 的 private copy constructor 可以解决问题,但有一个缺点: Rect 取决于 SpecialRect 声明。 [来自 Jarod42 的评论]
注意:请记住,您需要实现空构造函数,因为不会有默认构造函数。
class SpecialRect;
class Rect {
public:
Rect(){}
private:
Rect(const SpecialRect&);
//Rect(const SpecialRect&) = delete; // c++11
};
class SpecialRect : public Rect {
};
int main()
{
SpecialRect sr;
//Rect r1 = sr; // error: 'Rect::Rect(const SpecialRect&)' is private
//Rect r2(sr); // error: 'Rect::Rect(const SpecialRect&)' is private
Rect r3;
Rect r4(r3);
Rect r5 = r3;
return 0;
}
另一种解决方案是在 Rect 中声明显式默认复制构造函数。这具有不依赖于子类的好处,但有副作用。
class Rect {
public:
Rect(){}
explicit Rect(const Rect&);
};
class SpecialRect : public Rect {
};
int main()
{
SpecialRect sr;
//Rect r1 = sr; // Prevents this
Rect r2(sr); // Leaves this
Rect r3;
Rect r4(r3);
//Rect r5 = r3; // Side Effect: Prevents this
return 0;
}
关于c++ - 防止派生类强制转换为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36473354/