赋值运算符重载

时间:2019-02-21 09:08:31

标签: c++ oop operator-overloading

我正在尝试重载赋值运算符。给定

Point p1(1,2,3);
Point p2(1,2,3);
Point p3 = p1 + p2;
Point p4 = 22;
cout<< p4;

这是我的完整代码:

#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;

}

我无法在m_x,m_y,m_z中插入值22或任何值。我如何解决这条线:

Point p4 = 22;

2 个答案:

答案 0 :(得分:2)

这里有2个不同的问题。

Point p4 = 22;

这不是分配,实际上是对构造函数的调用。由于您声明的构造函数使用3个int作为默认值,因此可以使用1个,2个或3个值来调用它。

所以这等同于做这两者之一

Point p4(22, 0, 0);
Point p4(22);

如果要使用赋值运算符,则需要编写

Point p4;
p4 = 22;

但是在这里我们遇到第二个问题,您的赋值运算符创建一个新的Point并按值返回它。您要做的就是修改现有的。

Point& Point::operator=(int val){ // Return by reference
    m_x = m_y = m_z = val;
    return *this;
}

答案 1 :(得分:0)

您并不需要使+操作成为好友函数。

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;

}