c++ - 防止派生类强制转换为基类

标签 c++ inheritance casting object-slicing

我有

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/

相关文章:

c++ - 在 Visual Studio (2005) 下使用 Makefile 代替解决方案/项目文件

c++ - 尝试从源构建 Qt 会导致错误

c++ - 如何在 C/C++ 函数中返回 char* 数组?

c# - 这个关键字存在吗?当覆盖方法需要调用父方法时

javascript - 在 JavaScript 类中,子级可以默认调用其 super 父级方法吗?

java - 如何在 Java 中将 ArrayList 列表写入 CSV 格式

c++ - 如何从一组已定义的描述符中动态构建新的 protobuf?

java - 方法链接 : How to use getThis() trick in case of multi level inheritance

enums - C++/CLI : Casting from unmanaged enum to managed enum

c# - 使用 Type 类型的参数进行转换