簡體   English   中英

具有抽象類的C ++ 11對象組合

[英]C++11 object composition with abstract classes

假設我有一個Foo類,它具有抽象類Bar的const成員,那么在構造函數中傳遞Bar來初始化const成員的正確方法是什么?

class Foo
{
public:
    Foo(?Bar? bar): bar(?bar?) {};
private:
    const ?Bar? bar;
}

在C ++ 11中,我正在考慮像這樣使用std :: unique_ptr:

class Foo
{
public:
    Foo(std::unique_ptr<Bar> &bar): bar(std::move(bar)) {};
private:
    const std::unique_ptr<Bar> bar;
}

這是最好的方法嗎? 還有哪些其他方式?何時應使用它們?

在...

struct Foo
{
public:
    Foo(std::unique_ptr<Bar> &bar): bar(std::move(bar)) {};
    const std::unique_ptr<Bar> bar;
};

... bar(指針)不可修改,但指向的值是可修改的。

這是你想要的嗎?

我寧願認為:

class Foo
{
public:
    Foo(std::unique_ptr<const Bar>& bar): bar(std::move(bar)) {}

private
    std::unique_ptr<const Bar> bar;
};

會更合適,因為該值不是真正恆定的。 我懷疑這不會編譯,因為unique_ptr無法調用析構函數(自定義刪除程序的規范浮現在腦海),但是直方圖指向的值是const,這正是您真正想要的(我懷疑)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM