多態對象應該通過指針或引用訪問

多態對象應該通過指針或引用訪問

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


覺得本文有幫助?請分享給更多人。

面向對象開發,面向對象思考!


分享到:


相關文章: