相关疑难解决方法(0)

防止切片的惯用方式?

有时,c ++默认允许切片可能会令人烦恼。例如

struct foo { int a; };
struct bar : foo { int b; };

int main() {
    bar x{1,2};
    foo y = x; // <- I dont want this to compile!
}
Run Code Online (Sandbox Code Playgroud)

将编译并按预期运行!但是,如果我不想启用切片怎么办?

什么是惯用的写法,foo以至于无法对任何派生类的实例进行切片?

c++ inheritance object-slicing

17
推荐指数
2
解决办法
990
查看次数

标签 统计

c++ ×1

inheritance ×1

object-slicing ×1