2012-11-12 67 views
3

我有一個基類和多個派生類。每個派生類都有一個構造函數,它接受在基類中初始化的參數。所有的構造函數都是不同的,但它們都接受一個共同的參數,我們稱之爲Name從多個派生類中返回函數

有沒有辦法讓我顯示每個派生類的名字,而不是一個接一個地調用它們?

下面是一個例子。比方說,我的基類是Father和我的派生類是Brother, Sister, HalfBrother, HalfSister,這是我的驅動程序文件:

cout << Brother::Brother().getName() << endl 
    << Sister::Sister().getNAme() << endl 
    << HalfBrother::HalfBrother().getNAme() << endl 
    << HalfSister::HalfSister().getName() << endl; 

這將返回他們罰款,但有一個簡單的方法來做到這一點,這樣我可以得到所有的名字從所有的派生類中,而不必一一寫出它們?

+0

我不認爲我們可以這樣做,但可能是,如果我們使用超()或類似的東西則是可能的。我正在等待你的問題的回覆(回答)。 – SRJ

+0

你爲什麼要構造臨時對象來打印他們的名字,這個通用參數名稱在哪裏 - 我看到他們沒有使用任何參數? – PiotrNycz

+0

爲什麼不在父親中使用getName()方法?通過這樣做,您只需遍歷父引用/指針列表並調用'father-> getName()' –

回答

1

您可以創建類的靜態註冊表,並從您插入到您想要註冊的類的靜態成員的構造函數中填充它。

在標題:

class Registration { 
    static vector<string> registered; 
public: 
    static void showRegistered() { 
     for (int i = 0 ; i != registered.size() ; i++) { 
      cout << registered[i] << endl; 
     } 
    } 
    Registration(string name) { 
     registered.push_back(name); 
    } 
}; 

在CPP文件:

vector<string> Registration::registered; 

有了這個類在手,你可以這樣做:

在標題:

class A { 
    static Registration _registration; 
}; 

class B { 
    static Registration _registration;  
}; 

class C { 
    static Registration _registration;  
}; 

在CPP文件中:

Registration A::_registration("quick"); 
Registration B::_registration("brown"); 
Registration C::_registration("fox"); 

最後這部分是關鍵:靜態_registration變量的聲明有一個副作用 - 它們插入名稱到Registration類的vector<string> registered,在沒有特定的順序。您現在可以檢索這些名稱,將它們打印出來,或者做任何您想要的東西。我添加了一個用於打印的成員函數,但顯然你不受它的限制。

這裏是一個demo on ideone - 它打印

quick 
brown 
fox 
0

老實說,我不知道如果我理解你的問題。正如評論中所說,你應該在父親中使getName()成爲方法。

class Father { 
public: 

    Father(string name) : m_name(name) { 
    } 

    string& getName() { 
     return m_name; 
    } 

private: 
    string m_name; 
}; 

class Brother : public Father { 
public: 
    Brother(string name) : Father(name) { 
    } 
}; 

class Sister : public Father { 
public: 
    Sister(string name) : Father(name) { 
    } 
}; 

所以,你可以有這樣的:

vector<Father *> fathers; 
Brother brother("..."); 
Sister sister("...."); 

father.push_back(&brother); 
father.push_back(&sister); 

for (vector<Father*>::iterator itr = fathers.begin(); 
     itr != fathers.end(); 
     ++itr) { 
    cout << (*itr)->getName() <<endl; 
}