1.仮想関数の戻り値の型の文法規則
サブクラス(派生クラス)が親クラス(基本クラス)の仮想関数を実装する場合、元の戻り値の型と同じ戻り値の型を宣言する必要はなくなりました。関数の戻り値の型が親クラス(基本クラス)へのポインターまたは参照である場合、サブクラス(派生クラス)の関数は、親クラス(基本クラス)の派生クラスへのポインターまたは参照を返すことができます。
2.サンプル
#include <list>
struct NLComponent
{
virtual NLComponent* clone() const = 0;
// ...
};
struct TextBlock : NLComponent
{
virtual TextBlock* clone() const override
{
return new TextBlock(*this);
}
// ...
};
struct Graphic : NLComponent
{
virtual Graphic* clone() const override
{
return new Graphic(*this);
}
// ...
};
struct NewsLetter
{
NewsLetter() = default;
// 实现任何对象的copy
NewsLetter(const NewsLetter& rhs)
{
for(auto& component : rhs.components)
{
components.push_back(component->clone());
}
}
void add(NLComponent* component)
{
components.push_back(component);
}
private:
std::list<NLComponent*> components;
};
int main()
{
NewsLetter newsLetter;
newsLetter.add(new TextBlock());
newsLetter.add(new Graphic());
// copy
NewsLetter backup(newsLetter);
return 0;
}
NewsLetterは、仮想関数の戻り値ルールを使用することにより、NewsLetterによって集約されたオブジェクトをコピーできます。