簡體   English   中英

C ++:如何根據條件選擇構造函數?

[英]C++: how to choose the constructor depending on the condition?

假設我有一個具有不同構造函數的類:

class A
{
public:
    A(char* string)
    {
        //...
    }

    A(int value)
    {
        //..
    }

    void check() {}
};

現在我想在堆棧上創建一個A對象,必須根據某些條件選擇構造函數,但是有一個問題:創建的對象被破壞,然后我們退出{...}塊。

bool isTrue() { /*...*/ }

int main() 
{
    if (isTrue())
    {
        A a("string");
    }
    else
    {
        A a(10);
    }
    a.check(); //error: 'a' is not defined in this scope
}

假設我在A類中沒有copy-constructor或operator= 那么如何解決這個問題呢? http://ideone.com/YsjmnK

A a = isTrue() ? A("string") : A(10);

如果a.check()是const成員函數,則替代方法可能更好:

const A& a = isTrue() ? A("string") : A(10);

當參考對象將被銷毀a走出去的范圍。

因為C ++ 17注意,根據規則復制省略成為該情況下可訪問的復制/移動的構造不是必需的; 這里保證復制省略。

從C ++ 17開始,您可以使用std :: optional ,它不會引起任何動態內存分配。 例如

std::optional<A> a;
if (isTrue())
{
    a.emplace("string");
}
else
{
    a.emplace(10);
}
(*a).check();

順便說一句: A(char* string)應該是A(const char* string)

您不能滿足所有陳述的要求。

如果可以擺脫將對象放在堆棧上的要求,則可以使用指針。

A *a;
if (isTrue())
    a = new A("string");
else
    a = new A(10);
a->check();
delete a;

如果類型具有默認構造函數,則可以默認構造一個對象,立即對其進行銷毀,然后使用適當的構造函數通過placement-new重新構造它:

A a;
a.~A();
if (isTrue())
{
    new(&a) A("string");
}
else
{
    new(&a) A(10);
}

C ++標准有幾個類似於上面的示例,僅搜索.~->~

請注意,這是超邪惡的。 如果您的代碼曾經被審查過,您可能會被解雇。

我前一陣子有完全相同的問題,這是谷歌幫助我找到的:

unique_ptr<A> foo;

if(isTrue())
    foo = std::unique_ptr<A>(new A("10"));
else
    foo = std::unique_ptr<A>(new A(10));

對於OP來說可能為時已晚,但希望其他人可能會覺得有用。

您可以使用模板類:

template<class type> class A
{
protected:
    type    T;
public:

    void A(type t_curr) {T = t_curr;};//e.g.---

    void check() {}
};

暫無
暫無

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

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