从派生 类 添加对象

Adding objects from derived classes

我坚持在派生的 classes 之间使用运算符 +。这也是我第一次使用派生的 classes,所以任何提示都将不胜感激。

无论如何,代码:

// 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;
}

我想不出将两个派生的 class 对象相加的方法。有什么想法吗?

我尝试在派生的 class 中添加一个运算符函数,例如:

//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;
};

注意:我确信我添加键或返回字符串的方法正在运行。我只是不知道如何添加两个派生的 classes.

这似乎可以使用一些 模板

首先是基础atomclass

class atom
{
private:
    size_t bonds_;

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

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

然后 child classes

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+ 函数可能会破坏一些基本的化学规则。很久以前我对化学一无所知。 :)