C++ 从派生类添加对象
我一直坚持在派生类之间使用运算符+。这也是我第一次使用派生类,所以任何提示都将不胜感激 无论如何,代码:C++ 从派生类添加对象,c++,class,derived,C++,Class,Derived,我一直坚持在派生类之间使用运算符+。这也是我第一次使用派生类,所以任何提示都将不胜感激 无论如何,代码: // 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 return
// 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;
}
注意:我确信我添加键或返回字符串的方法能够正常工作。我就是不知道如何添加两个派生类。这似乎需要一些模板 首先是基本的
atom
类
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}
{}
};
最后是模板化的操作符+
函数
template<typename A, typename B>
B operator+(A a, B b)
{
// TODO: b.add_bonds(1, a);
return b;
}
或
或者更一般地说
auto new_atom = h + c; // or c + h
重要免责声明:提供的
操作员+
功能可能会阻止一些基本的化学规则。我对化学一无所知已经很久了 您希望在基类上定义\u bonds
字段和+
运算符,这样您就可以“添加”从atom
派生的任何两个类
h = c + h;
c = h + c;
auto new_atom = h + c; // or c + h