Bjarne Stroustrup 的 The C++ Programming Language Fourth Edition 中的以下内容是什么意思?
"Consider . (dot) suspect when applied to something that is supposed to be run-time polymorphic unless it is obviously applied to a reference."
最佳答案
这与 object slicing in C++ 有关.
说你有
struct Base
{
virtual void print() { std::cout << "In Base::print()\n"; }
};
strut Derived : Base
{
virtual void print() { std::cout << "In Derived::print()\n"; }
};
现在您可以将它们用作:
void test(Base base)
{
base.print();
}
int main()
{
Derived d;
test(d);
}
当你这样使用它时,你的程序会遇到对象切片问题。 test
中的base
不保留有关Derived
的任何信息。它被分割成一个 Base
。因此,您将获得的输出将对应于 Base::print()
的输出。
如果您使用:
void test(Base& base)
{
base.print();
}
int main()
{
Derived d;
test(d);
}
程序不存在对象切片问题。它以多态方式工作,输出将对应于 Derived::print()
的输出。
注意事项对应于 test
第一版中 base.print()
的使用。它使用 。 (点)
对象上的运算符是多态类型,而不是引用。
关于c++ - 考虑 。 (点)当应用于应该是运行时多态的东西时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48879047/