派生したクラス間で演算子+を使用することに固執しています。これは私の派生クラスでの作業でも初めてのことですので、ヒントをいただければ幸いです。とにかく派生クラスからオブジェクトを追加する
、コード:
// 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つの派生クラスを追加する方法を見つけることができません。
基本クラスに '_bonds'フィールドと' + '演算子を定義したい場合、' atom'から派生した2つのクラスを "追加"できます –