Line 7: Don't write
V(void)
-- instead write
V()
.
Lines 8-12: Line 10 is a problem, because an assignment operator is supposed to make a copy of its argument. It
should look like this:
1 2 3 4 5
|
V& operator=(const V &arg) {
for (int i=0; i<2; i++) // Loop, i=0,1,... while less than 2
vec[i] = arg.vec[i]; // Copy corresponding element
return *this;
}
|
The problem with your line 10 is that it is not making a copy of its argument, but doing something different.
For example, suppose you have the following code:
1 2 3 4 5 6 7 8
|
int main() {
int x = 5;
int y;
y = x;
cout << y << "\n";
}
|
7 |
What would you expect the output to be? Does it make sense that the output is "7"?
No, of course not. The output should have been "5".
Likewise, when assigning one object to another, the objects should have the same values.
If you want to do something odd, like swap the first and last elements in a 2D vector, then that should be a member function:
1 2 3 4 5 6 7 8
|
class V {
public:
...
void reverse() {
int temp = v[0];
v[0] = v[1];
v[1] = temp;
}
|
Now in your code, you can do it explicitly:
1 2 3 4 5
|
int main() {
V a( 3, -7 );
a.reverse();
cout << "(" << a.vec[0] << ", " << a.vec[1] << ")" << endl;
}
|
(-7, 3) |
Yay!
Hope this helps.