有时,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以至于无法对任何派生类的实例进行切片?