Task:1
A single point has two coordinates p1(x,y). Create a class name Point with a length 2 array asit's private data member. Initialize the array using constructor. Overload array subscript operator ‘[ ]’ for if I have to access the object's array at a particular index from main function
like this.
Point p1(1, 1);
cout << p1[0] << " " << p1[1] << endl;
Task#02:
Copy paste the same task and do consider doing it in dynamic memory instead of static. Plus alter the subscript overloaded function for if I have to make changes to the class array from the main function. Hint: By reference
Point p2(3, 3);
cout << p2[0] << " " << p2[1] << endl;
p2[0] = 7;
p2[1] = 9;
cout << p2[0] << " " << p2[1] << endl;
Task1
#include <iostream>
using namespace std;
class Point {
public:
Point(double x, double y);
double& operator[](int i);
double operator[](int i) const;
private:
double data[2];
};
Point::Point(double x, double y) {
data[0] = x;
data[1] = y;
}
double& Point::operator[](int i) {
return data[i];
}
double Point::operator[](int i) const
{
return data[i];
}
int main() {
Point p1(1, 1);
cout << p1[0] << ' ' << p1[1] << endl;
return 0;
}
Task2
#include <iostream>
using namespace std;
class Point {
public:
Point(double x, double y);
Point(const Point& p);
~Point();
Point& operator=(const Point& p);
double& operator[](int i);
double operator[](int i) const;
private:
double *data;
};
Point::Point(double x, double y) {
data = new double[2];
data[0] = x;
data[1] = y;
}
Point::Point(const Point& p) {
data = new double[2];
data[0] = p.data[0];
data[1] = p.data[2];
}
Point::~Point() {
delete [] data;
}
Point& Point::operator=(const Point& p) {
if (&p == this) {
return *this;
}
delete [] data;
data = new double[2];
data[0] = p.data[0];
data[1] = p.data[2];
return *this;
}
double& Point::operator[](int i) {
return data[i];
}
double Point::operator[](int i) const
{
return data[i];
}
int main() {
Point p2(3, 3);
cout << p2[0] << ' ' << p2[1] << endl;
p2[0] = 7;
p2[1] = 9;
cout << p2[0] << ' ' << p2[1] << endl;
return 0;
}
Comments
Leave a comment