<分区>
例如,考虑:
class Deriv : public Base {...};
...
bar(Deriv d);
bar(Base b);
foo(Base b) {bar(b);}
...
Deriv x;
foo(x); // does x get treated as Base for the bar() call
// or retain its Deriv type?
如果 foo
通过引用传递呢?
<分区>
例如,考虑:
class Deriv : public Base {...};
...
bar(Deriv d);
bar(Base b);
foo(Base b) {bar(b);}
...
Deriv x;
foo(x); // does x get treated as Base for the bar() call
// or retain its Deriv type?
如果 foo
通过引用传递呢?
最佳答案
您正在按值传递,因此您正在创建一个 Base 类型的新对象并为其分配一个拷贝..
非常糟糕,你会遇到切片......它不会保留它的阶段,不建议。 http://en.wikipedia.org/wiki/Object_slicing
要么通过引用传递,要么通过 const 引用传递,后者更好更快:
bar(const Base& b)
或传递一个指向对象的指针,您将保留状态。 酒吧(基础* b);
这将是处理此问题的正确方法。
关于c++ - 传递给接受基类的函数的变量是否仍然保留它们最派生的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16598930/