I'm learning about class operators and am stuck. I'm trying a simple class that defines an x,y point. The code then multiplies the x and y values of that point by 4 and spits out the new values. When I compile this, I get the following error on the line in bold:
"error C2804: binary 'operator *' has too many parameters"
Here is the code:
// 13.1.2.cpp : main project file.
#include "stdafx.h"
#include <iostream>
using namespace std;
class Point {
private:
int x,y; //Data Members
public:
//Constructors
Point() {x=0; y=0;}
Point(int new_x, int new_y) {set(new_x, new_y);}
Point(const Point &src) {set(src.x, src.y);}
//Operations
Point mult(const int &n, const Point &pt); Point operator*(const int n, Point &pt) {return mult(n, pt);}
//Other member functions
void set(int new_x, int new_y);
int get_x() const {return x;}
int get_y() const {return y;}
};
int main()
{
Point point1(20, 25); //Create a new Point objects
Point point2 = 4 * point1; //Create another new point that is 4x the value of point1
cout << "The value of point2 is " << point2.get_x();
cout << ", " << point2.get_y() << "." << endl << endl;
system("PAUSE");
return 0;
}
void Point::set(int new_x, int new_y) {
x = new_x;
y = new_y;
}
Point Point::mult(const int &n, const Point &pt) {
Point new_pt;
new_pt.x = n * pt.x;
new_pt.y = n * pt.y;
return new_pt;
}
OK....you have a few mistakes. I don't know whether you know this but... Your operator* definition is wrong. When you call it like you did here:Point point2 = 4 * point1; compiler turns that intopoint1.operator*(4); which, of course, doesn't match parameters declared in operator* prototype. Operator* is binary, which means it needs 2 operands, and because you declared it within class Point (not as global function), you don't need to pass object explicitly. So:
class Point
{
//......
//Operations
Point mult(int n );
Point operator*(int n) {return mult(n);}
//.....
};
int main()
{
//....
Point point2 = point1 * 4; //Create another new point that is 4x the value of point1
//.....
return 0;
}
//....
Point Point::mult(int n) {
Point new_pt;
new_pt.x = n * (*this).x;//uses dereferenced this pointer
new_pt.y = n * (*this).y;//uses dereferenced this pointer
return new_pt;
}
Thank you. I'm not surprised about the multiple mistakes. One other mistake that I made was not explaining the point of the exercise that I am working on. This is an exercise that has two objectives: 1) to learn about global / friend functions and 2) about improving efficiency with references. So, I need to keep those ideas in my code, even though I don't think that I did with my original post.
I'm totally confused about how to do this, and I think that the book that I am studying does a terrible job explaining it. Can somebody see what I am doing wrong in my original code with these two ideas?