2017-06-26 4 views
1

派生したクラス間で演算子+を使用することに固執しています。これは私の派生クラスでの作業でも初めてのことですので、ヒントをいただければ幸いです。とにかく派生クラスからオブジェクトを追加する

、コード:

// Base class 
class atom { ... } 
// Not quite sure what the base class needs 

//derived class 
class hydrogen: public atom { 
private: 
    double bonds_ = 1; 
public: 
//other code 
//method that returns string of bonds_ 
//method that adds bonds_ 
} 

//derived class 
class carbon: public atom { 
private: 
    double bonds_ = 4; 
public: 
//other code 
//method that returns a string of bonds_ 
//method that adds bonds_ 
} 

int main(){ 
hydrogen h; 
carbon c; 

h = c + h; 
// adding a derived class with another 

std::cout << h.get_bond_string() << std::endl; 
//should be 5 

return 0; 
} 

私は2つの派生クラスのオブジェクトを追加する方法を把握することはできません。何か案は?

私は次のように、派生クラスでオペレータ機能を追加しようとしました:

//in the carbon derived class, 

hydrogen carbon::operator+(hydrogen h){ 
    carbon c; //creates a default carbon c 
    h.add_bonds(c, 1); 

//adds the bonds together; first parameter is the element, 
//second parameter is quantity of the element 


return h; 
}; 

注:私は、債券を追加したり、文字列を返すための私の方法が機能している確信しています。私はちょうど2つの派生クラスを追加する方法を見つけることができません。

+0

基本クラスに '_bonds'フィールドと' + '演算子を定義したい場合、' atom'から派生した2つのクラスを "追加"できます –

答えて

2

テンプレートを使用できるようです。

まず基本的な​​クラス

class atom 
{ 
private: 
    size_t bonds_; 

public: 
    explicit atom(size_t const bonds) 
     : bonds_{bonds} 
    {} 

    // Other functions... 
    // For example the `add_bonds` function 
}; 

そして、子クラス

struct hydrogen : public atom 
{ 
    hydrogen() 
     : atom{1} 
    {} 
}; 

struct carbon : public atom 
{ 
    carbon() 
     : atom{4} 
    {} 
}; 

そして最後に、テンプレートoperator+機能

template<typename A, typename B> 
B operator+(A a, B b) 
{ 
    // TODO: b.add_bonds(1, a); 
    return b; 
} 

これは、あなたが

を書くことができます
h = c + h; 

又は

c = h + c; 

またはより一般

auto new_atom = h + c; // or c + h 

重要な免責事項:operator+機能設け月ブレーキいくつかの基本的な化学ルールなど。それは私が化学について何か知って以来、長いことでした。 :)

+0

ありがとう!これは機能します。私はあなたの助けに感謝します! –

関連する問題