Overloading addition operator with many objects c++ -


i need overload addition operator of multiple different objects , return 'cluster object: "overload addition operator(+) add combination of instances desktops, laptops, , clusters. operator should return object of type cluster" if had desktop1+laptop1+laptop2; need return cluster adds of ram, , other variables of each object. adding variables of objects inherit computer class. here code of rest of project. thanks!

#include <iostream>  using namespace std;  class computer {     public:         double ram;         double cpuspeed;         int numberofcores;         double hddsize;         virtual void print(); }; class desktop : public computer {     public:         bool hasmonitor;         double monitorsize;         friend istream& operator>> (istream &in, desktop &mydesktop); }; class laptop : public computer {     public:         double screensize; }; class cluster : public computer {     public:         int numofcomp; }; desktop::desktop() {     ram = 0;     cpuspeed = 0;     numberofcores = 0;     hddsize = 0;     hasmonitor = 0;     monitorsize = 0; } laptop::laptop() {     ram = 0;     cpuspeed = 0;     numberofcores = 0;     hddsize = 0;     screensize = 0; } cluster::cluster() {     ram = 0;     cpuspeed = 0;     numberofcores = 0;     hddsize = 0;     numofcomp = 0; } istream& operator>> (istream &in, desktop &mydesktop) {     in >> mydesktop.hasmonitor;     in >> mydesktop.monitorsize;     in >> mydesktop.ram;     in >> mydesktop.cpuspeed;     in >> mydesktop.hddsize;     in >> mydesktop.numberofcores;     return in; } istream& operator>> (istream &in, laptop &mylaptop) {     in >> mylaptop.ram;     in >> mylaptop.cpuspeed;     in >> mylaptop.hddsize;     in >> mylaptop.numberofcores;     in >> mylaptop.screensize;     return in; } istream& operator>> (istream &in, cluster &mycluster) {     in >> mycluster.ram;     in >> mycluster.cpuspeed;     in >> mycluster.hddsize;     in >> mycluster.numberofcores;     in >> mycluster.numofcomp;     return in; } operator+(computer &mycomp) {     return  

if want add values common classes inherit computer, can this:

cluster operator+(const computer& comp1, const computer& comp2) {     cluster ret;     ret.ram = comp1.ram+comp2.ram;     ret.cpuspeed = comp1.cpuspeed+comp2.cpuspeed;     ret.numberofcores = comp1.numberofcores+comp2.numberofcores;     ret.hddsize = comp1.hddsize+comp2.hddsize;     return ret; }  int main() {     laptop laptop1;     desktop desktop1;     desktop desktop2;     cluster mycluster = laptop1+desktop1+desktop2;     return 0; } 

the chained + operators evaluated right leftwards. function returns cluster object, can used right hand operand next addition.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -