Why doesn't my C ++ object affect another C ++ object?

I have a simple C ++ class, intHolder, which only contains int. It can also add to this an int that works, or add itself to another int contained in another intHolder that doesn't work. This is not what I came across in Java. What's happening?

class intHolder{
private:
    int i;
public:
    intHolder(int myInt){i = myInt;}
    void addToInt(int inc){ i = i + inc;}
    void printInt(){cout << i << endl;}
    void addToOtherInt(intHolder other){other.addToInt(i);}
};

Main method

int main () {
    intHolder ih1(1);
    ih1.printInt();//Should be 1, is 1
    ih1.addToInt(3);
    ih1.printInt();//Should be 4, is 4
    intHolder ih2(2);
    ih2.printInt();//Should be 2, is 2
    ih1.addToOtherInt(ih2);
    ih1.printInt();//Should be 4, is 4
    ih2.printInt();//Should be 6, is 2
};
+3
source share
1 answer

You pass value intHolderby value. This means that the function acts on the local copy, so there is no effect on the caller’s side. You need to pass the link:

void addToOtherInt(intHolder& other) { other.addToInt(i); }
                            ^

, , , , , , ,

intHolder a = 5;
intHolder b = 10;
intHolder c = a + b;
c += 42;
a = 42 - b;

.. . .

, "" ostream& operator<<, , , , std::cout. :

struct Foo
{
  int i;
};

std::ostream& operator<<(std::ostream& o, const Foo& f)
{
  return o << f.i;
}

Foo f;
std::cout << f;
std::cerr << f;
std::ofstream tmp("foo.txt");
tmp << f;
+13

All Articles