Reputation: 434
I was trying to overload assignment operator. Given
Point p1(1,2,3);
Point p2(1,2,3);
Point p3 = p1 + p2;
Point p4 = 22;
cout<< p4;
Here is my full code:
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
class Point{
private:
int m_x, m_y, m_z;
public:
Point(int x=0, int y = 0, int z = 0):m_x(x), m_y(y), m_z(z)
{
}
friend Point operator+(Point &p1, Point &p2);
friend ostream& operator<<(ostream &out, Point &p);
Point operator=(int val);
};
Point operator+(Point &p1, Point &p2){
return Point(p1.m_x+p2.m_x , p1.m_y+ p2.m_y , p1.m_z+p2.m_z);
}
ostream& operator<<(ostream &out, Point &p){
out<<"output: "<<p.m_x<<" "<<p.m_y<<" "<< p.m_z<<'\n';
return out;
}
Point Point::operator=(int val){
return Point(val, val, val);
}
int main(){
Point p1(1,2,3);
Point p2(1,2,3);
Point p3 = p1 + p2;
Point p4 = 22;
cout<< p4;
}
I can't insert the value 22 or any value in m_x, m_y ,m_z. How can I solve the line:
Point p4 = 22;
Upvotes: 2
Views: 139
Reputation: 138
And you don't need to make the + operation a friend function.
using namespace std;
class Point {
public:
Point() {}
Point(int x , int y , int z ) :m_x(x), m_y(y), m_z(z)
{
}
Point& operator+(const Point &p1);
friend ostream& operator<<(ostream &out, Point &p);
Point& operator=(int val);
private:
int m_x, m_y, m_z;
};
Point& Point::operator+(const Point& p1)
{
Point temp;
temp.m_x = this->m_x + p1.m_x;
temp.m_y = this->m_y + p1.m_y;
temp.m_z = this->m_z + p1.m_z;
return temp;
}
ostream& operator<<(ostream &out, Point &p) {
out << "output: " << p.m_x << " " << p.m_y << " " << p.m_z << '\n';
return out;
}
Point& Point::operator=(int val) { // Return by reference
m_x = m_y = m_z = val;
return *this;
}
int main() {
Point p1(1, 2, 3);
Point p2(1, 2, 3);
Point p3 = p1 + p2;
Point p4;
p4 = 22;
cout << p4;
}
Upvotes: 0
Reputation: 12928
The are 2 different problems here.
Point p4 = 22;
This is not an assignment, it's actually a call to a constructor. Since you declared your constructor that takes 3 int
s with default values, it can be called with 1, 2 or 3 values.
So it's equivalent of doing either of these two
Point p4(22, 0, 0);
Point p4(22);
If you want to use the assignment operator you need to write
Point p4;
p4 = 22;
But here we run in to the second problem, your assignment operator creates a new Point
and returns it by value. What you want to do is modify the existing one.
Point& Point::operator=(int val){ // Return by reference
m_x = m_y = m_z = val;
return *this;
}
Upvotes: 2