AM> What's wrong with this code? I guess the temporary object created in
AM> operator+ member is lost somewhere, but I don't know why, and I don'
AM> know how to make it work :-(
What doesn't work? What's the output of the main() function? I don't
see any "fatal" problems in your code. But allow me some remarks:
AM> #include
AM> #include
AM> #include
AM> #include
Only the #inclusion of iostream.h is necessary.
AM> #if !defined(max)
AM> #define max(a, b) ((a) > (b) ? (a) : (b)) // ridiculous...
AM> #endif
max is not needed. If you need it, use a template. If you really want
it to be a vector, erase the comment.
AM> class Vector
AM> {
AM> public:
AM> double x, y;
Don't make these public. Better declare them private and provide
inline accessor methods:
private:
double x, y;
public:
double X() const { return x; }
double Y() const { return y; }
AM> Vector(double xx = 0, double yy = 0); // constructor
This constructor may cause you problems (not in the main() function
you give below, though) like every constructor taking one argument: it
can be used by the compiler for implicit conversions.
AM> Vector::Vector(double xx, double yy)
AM> {
AM> x = xx;
AM> y = yy;
AM> }
AM> Vector::Vector(const Vector & V2)
AM> {
AM> x = V2.x;
AM> y = V2.y;
AM> }
Initialize the members in the member-initializer-list rather than in
the constructor's body:
Vector::Vector(double xx, double yy)
: x(xx),
y(yy)
{
}
Vector::Vector(const Vector & V2)
: x(V2.x),
y(V2.y)
{
}
AM> Vector Vector::operator+(const Vector & V2) const
AM> {
AM> Vector add;
AM> add.x = x + V2.x;
AM> add.y = y + V2.y;
AM> return add;
AM> }
No problem here, this is correct.
AM> Vector & Vector::operator=(const Vector & V2)
AM> {
AM> if (this != &V2) {
AM> x = V2.x;
AM> y = V2.y;
AM> }
AM> return *this;
AM> }
ú [ Continued In Next Message... ]
--- PCBoard (R) v15.22/M 25
---------------
* Origin: McMeier & Son BBS (2:301/138)
|