c++ - 考虑 。 (点)当应用于应该是运行时多态的东西时

标签 c++

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/

相关文章:

c++ - 声明或定义

c++ - 如何将整数变量转换为 QTime 对象

c++ - OpenCL 内置函数选择

c++ - Eclipse C++ 调试器不显示变量值

c++ - MSVC : Implicit Template Instantiation, 虽然未使用模板化构造函数

c++ - 关于vector reserve large memory的问题

c++ - 将 char* 替换为 shared_ptr<char>

c++ - 在 C++ 中格式化每个媒体的程序

c++ - 遍历 multimap 中的一个组我怎么知道我是在第一个还是最后一个元素中?

c++ - 如何使用 Qpainter 将多个 qwidgets 打印到不同页面中的 pdf?