多态对象应该通过指针或引用访问

多态对象应该通过指针或引用访问

C.145: Access polymorphic objects through pointers and references

C.145:通过指针或引用访问多态对象

Reason(原因)

If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.

如果有一个类有虚函数,通常不会知道使用的函数具体是由那个类提供的。

Example(示例)
<code>struct B { int a; virtual int f(); virtual ~B() = default };
struct D : B { int b; int f() override; };

void use(B b)
{
D d;
B b2 = d; // slice
B b3 = b;
}

void use2()
{
D d;
use(d); // slice
}/<code>

Both ds are sliced.

两个(函数中的)d都被切断了(因为派生类对象向基类对象赋值,译者注)

Exception (例外)

You can safely access a named polymorphic object in the scope of its definition, just don't slice it.

你可以在多态对象被定义的作用域中通过变量名安全地使用它,主要注意不被切断就行。

<code>void use3()
{
D d;
d.f(); // OK
}/<code>
See also(参见)

A polymorphic class should suppress copying(多态类应该抑制复制)


Enforcement

Flag all slicing.(标记发生数据切断的操作)

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c145-access-polymorphic-objects-through-pointers-and-references


觉得本文有帮助?请分享给更多人。

面向对象开发,面向对象思考!


分享到:


相關文章: