簡體   English   中英

根據C ++中的輸入參數使對象屬於類

[英]Making an object belonging to a class depending on input parameters in C++

我正在嘗試建立一個對象,該對象的類型取決於輸入參數。 例如,我的對象稱為“進程”,並且在運行時輸入2到5之間的一個整數(含2和5)(包括整數),並且會發生如下情況:

if (input == 2) TwoJ   process;
if (input == 3) ThreeJ process;
if (input == 4) FourJ  process;
if (input == 5) FiveJ  process;

顯然,以上操作將不起作用,因為該對象會立即超出范圍。 有沒有辦法很好地實現這一目標? 干杯

使用工廠函數 ,該函數智能指針返回到基本Process類,並且其實現由提供給該工廠函數的整數值確定(要求所有類都具有公共基數)。

例如:

class Base_process
{
public:
    virtual ~Base_process() {}
    virtual void do_something() = 0;
};

class TwoJ : public Base_process
{
public:
    void do_something() {}
}
class ThreeJ : public Base_process
{
public:
    void do_something() {}
}

std::unique_ptr<Base_process> make_process(int a_type)
{
    if (a_type == 1) return std::unique_ptr<Base_process>(new TwoJ());
    if (a_type == 2) return std::unique_ptr<Base_process>(new ThreeJ());

    // Report invalid type or return an acceptable default if one exists.
    throw std::invalid_argument("Unknown type:" + std::to_string(a_type));
}

一種工廠方法

std::unique_ptr<ProcessType> CreateProcess(int input){ 
    if(input == 2) return std::unique_ptr<ProcessType>(new TwoJ());
    .....
}

當然,這假定您使用的各種類都有一個公共的基類,這里為ProcessType ,並且您對通過基類指針與其進行交互感到滿意。

您可以,但是所有這些都需要一個基類,例如

Base* process;

if (input == 2) process = new TwoJ();
if (input == 3) process = new ThreeJ();

然后訪問這些類,您需要做的是:

if (input == 2) (TwoJ*)process->someTwoJMethod();

或使用dynamic_cast:

TwoJ* p = dynamic_cast<TwoJ*>(process);
if(p != 0) {
   p->someTwoJMethod();
}

使用此方法,您有責任在對象超出范圍時刪除對象。 前面的答案是使用std::unique_ptr的cpp中的最佳方法,當對象超出范圍時,該對象將被自動刪除。

暫無
暫無

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

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