考虑 .(点)应用于应该是运行时多态性的东西时

  • 本文关键字:多态性 运行时 应用于 考虑 c++
  • 更新时间 :
  • 英文 :


Bjarne Stroustrup的C 编程语言第四版中的以下含义是什么?

"考虑。 除非显然将其应用于一个运行时多态性 参考。"

这与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()。它使用. (dot)运算符在是多态类型的对象上,而不是参考。

最新更新