I'm learning C++ from C++ Primer Plus, 5th Edition, and have come across the following problem.
The following class declaration is given as part of the question:
/*
Name: move.h
Copyright:
Author: Steven Taylor
Date: 31/01/08 15:05
Description: Class 'Move' header file. C++ Primer Plus, Ch.10,Prog. Ex 6.
*/
#ifndef MOVE_H_
#define MOVE_H_
class Move
{
private:
double x;
double y;
public:
Move(double a = 0, double b = 0); // sets x, y to a, b
void showmove() const; // shows current x, y values
Move add(const Move &m) const;
// this function adds x of m to x of invoking object to get new x,
// adds y of m to y of invoking object to get new y, creates a new
// move object initialized to new x, y values and returns it
void reset(double a = 0, double b = 0); // resets x,y to a, b
};
#endif
The question continues. Create member function definitions and a program that exercises the class.
The gist of my question surrounds the prototype/function Move add(const Move &m) const;
. I keep getting a compiler error that indicates 29 ...move.cpp assignment of data-member `Move::x' in read-only structure
. When I remove the const
reference at the end of the add function, the program compiles successfully and the function changes the private variables. If leaving that const
reference in place, as per my book, is there another way to modify the private variables.
This is what I've done so far:
/*
Name: move.cpp
Copyright:
Author: Steven Taylor
Date: 31/01/08 15:14
Description: Class methods for move. C++ Primer Plus, Ch.10. PE 5. Page 498
*/
#include <iostream>
#include "move.h"
using std::cout;
using std::endl;
Move::Move(double a, double b)
{
x = a;
y = b;
}
void Move::showmove() const
{
cout << "x = " << x << " y = " << y << endl;
}
Move Move::add(const Move &m) const
{
//double c, d;
//c = x + m.x;
//d = y + m.y;
//x = c;
//y = d;
x += m.x;
y += m.y;
Move *temp = new Move(x, y);
return *temp;
}
void Move::reset(double a, double b)
{
x = y = 0;
}
and the main program;
/*
Name: main.cpp
Copyright:
Author: Steven Taylor
Date: 31/01/08 15:27
Description: C++ Primer Plus, Ch. 10, Prog. Ex. 6, page 498.
*/
#include <iostream>
#include "move.h"
int main()
{
using std::cout;
using std::cin;
cout << "Move one\n";
Move one;
one.showmove();
cout << "\n\nMove two\n";
Move two(101.5,55.6);
two.showmove();
cout << "\n\nMove three\n";
Move three = one.add(two);
three.showmove();
cout << "\n\nMove one - after 'one.add(two)'\n";
one.showmove();
cout << "\n\nMove one - reset\n";
one.reset();
one.showmove();
cout << "\n\nMove two - reset\n";
two.reset();
two.showmove();
cout << "\nMove three - reset\n";
three.reset();
three.showmove();
// exit routine
cout << "\n\n...Press ENTER to Exit System...";
cin.get();
return 0;
}
Any advice appreciated.