dimanche 1 mai 2022

How is a=a+b diffrent from a+=b? [duplicate]

class komunikator {
        public:
            virtual ~komunikator() {}
            virtual ostream& opis(ostream&)const = 0;
            friend ostream& operator<<(ostream& out, const komunikator& r);
        };
        ostream& operator<<(ostream& out, const komunikator& r) {
            return r.opis(out);
        }
        
        class k1 : public komunikator {
        private:
            string* nazwa;
        public:
            k1() :nazwa(new string()) {}
            k1(const string& a1) :nazwa(new string(a1)) {}
            ostream& opis(ostream& napis)const {
                return napis << *nazwa<<endl;
            }
            ~k1(){}
        };
        
        class k2 : public komunikator {
        private:
            string* nazwa;
            int liczba;
        public:
            k2() :nazwa(new string()),liczba(0) {}
            k2(const string& a1,const int& a2) :nazwa(new string(a1)),liczba(a2) {}
            ostream& opis(ostream& napis)const {
                return napis << *nazwa <<" " <<liczba<< endl;
            }
            int& num() {
                return liczba;
            }
        
            const int& num() const {
                return liczba;
            }
        
            k2 operator+(const int& pa) {
                k2 copy(*this);
                copy.num() = copy.num() + pa;
                return copy;
            }
        
            k2 operator+=(const int& pa) {
                k2 copy(*this);
                copy.num() += pa;
                return copy;
            }
            ~k2() {}
        };
        
        int main() {
        
            const k1 koniec("Koniec komunikatow:");
        
            komunikator* linia[5];
            linia[0] = new k1("Temparatury powietrza:");
            linia[1] = new k2("Czestochowa", -5);
            linia[2] = new k1("Opady sniegu (cm):");
            linia[3] = new k2("Katowice", 10);
            linia[4] = new k1(koniec);
            
            for (int i = 0; i < 5; i++)
                cout << *linia[i];
        
            cout << "********3*********" << endl;
        
            *(static_cast<k2*>(linia[1])) = *(static_cast<k2*>(linia[1])) + 2;
            *(static_cast<k2*>(linia[3])) += 2;
        
            for (int i = 0; i < 5; i++) {
                cout << *linia[i];
                delete linia[i];
            }
        
            cout << "********4*********" << endl;
    return 0;
    }

There is only one thing I want to fix, but I don't know why "k2 operator+" returns diffrent value than "k2 operator+="? Operator "+" Works as expected, increased value of variable by 2 but operator"+=" did not change anything. (code between *****3 and *****4). How to solve this to work as I want to?

Aucun commentaire:

Enregistrer un commentaire