簡體   English   中英

創建一個變量來保存不同類型C ++的對象

[英]Create a variable to hold objects of different types C++

我有3個不同的對象ABC 根據給定的參數,我想在這些不同的對象中進行選擇。 在編程中,

class A { 
  public: 
    void printHello() { cout << "HELLO A" << endl; }
}; 

class B { 
  public: 
    void printHello() { cout << "HELLO B" << endl; }  
};

class C { 
   public: 
     void printHello() { cout << "HELLO C" << endl; }  
}; 

int main () { 
    string key = "c"; 
    A a; 
    B b; 
    C c; 
    Object obj; // I don't know how to declare Object. 

    if (key == "a") obj = a; 
    else if (key == "b") obj = b; 
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0; 
} 

我考慮過模板和結構對象。 但到目前為止他們都沒有工作。

template<typename T1, T2, T3> 
T1 getType(string key, T1 t1, T2 t2, T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1; 
    else if (key == "b") return t2; 
    else return t3; 
} 

創建Object o;很容易Object o; JAVA因為Java中的每個對象都是Object類的子類。 但是我如何在C ++中實現這一目標呢?

編輯。 我不能改變ABC 我得到了這些課程,我的目標是實現main方法。 所以, inheritance對我來說是不可能的。 對不起任何困惑。

任何幫助表示贊賞。

您正在尋找variant類型。 在C ++ 17中有一個即將發布的std::variant ,以及在boost和Web上的C ++ 11兼容版本。 使用boost::variant示例:

struct visitor
{
    void operator()(const A&){ cout << "HELLO A" << endl; }
    void operator()(const B&){ cout << "HELLO B" << endl; }
    void operator()(const C&){ cout << "HELLO C" << endl; }
};

int main()
{
    visitor v;

    // `obj` is either an `A`, a `B` or a `C` at any given moment.
    boost::variant<A, B, C> obj{B{}};
    //                         ^^^^^
    //                   Initialize with `B`.

    boost::apply_visitor(v, obj); // prints "HELLO B"

    obj = A{};
    boost::apply_visitor(v, obj); // prints "HELLO A"
}

在我看來,您應該使用虛擬公共基類/結構和指向此基類/結構的指針。

以下是一個完整的工作示例

#include <iostream>

struct Base
 { virtual void printHello () = 0; };

class A : public Base { 
  public: 
    void printHello() { std::cout << "HELLO A" << std::endl; }
}; 

class B  : public Base{ 
  public: 
    void printHello() { std::cout << "HELLO B" << std::endl; }  
};

class C  : public Base{ 
   public: 
     void printHello() { std::cout << "HELLO C" << std::endl; }  
}; 

int main () { 
    std::string key = "c"; 
    A a; 
    B b; 
    C c; 
    Base * obj; 

    if (key == "a") obj = &a; 
    else if (key == "b") obj = &b; 
    else obj = &c;
    obj->printHello(); // print Hello C.
    return 0; 
} 

你可以做點什么

if (key == "a") obj=new A();
else if (key == "b")  obj=new B();

暫無
暫無

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

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