考虑 .(点)应用于应该是运行时多态性的东西时
Consider . (dot) when applied to something that is supposed to be run-time polymorphic
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)
运算符在是多态类型的对象上,而不是参考。
相关文章:
- 为什么我们实际上需要运行时多态性?
- 运行时多态性和dynamic_cast需要澄清
- 运行时多态性 - 箭头运算符访问了错误的成员?
- C ++中的方法覆盖:是编译时还是运行时多态性?
- 运行时与编译时多态性:更好的可读性与编译时错误检查,更重要的是
- 两个不同类的运行时多态性
- 考虑 .(点)应用于应该是运行时多态性的东西时
- 编译时多态性运行时多态性是这样的吗
- CRTP的运行时多态性设计和策略
- 查询C++中的运行时多态性
- 需要使用模板解决运行时多态性的帮助
- 为什么不能在编译时解决运行时多态性?
- 尝试使用多态性C++时发生编译错误
- c++与java中运行时多态性的成本比较
- 为什么为模板实例化声明运行时多态性会导致链接器错误
- 编译时与运行时多态性在c++中的优缺点
- 允许运行时和编译时多态性的灵活方式
- c++中通过虚函数实现的运行时多态性
- 虚拟函数是在C++中实现运行时多态性的唯一途径吗
- c++中运行时和编译时多态性的区别