【问题标题】:C++: Binary operator overloading using member functionC++:使用成员函数的二元运算符重载
【发布时间】:2021-04-21 05:16:42
【问题描述】:

我搜索了一下stackoverflow,发现了一些与我正在做的事情相似的主题。但是,我只是不明白我犯的可能非常简单的错误。

你能帮帮我吗?如您所见,我犯了非常基本的错误。

该功能仅用于练习目的。我想为带有xy 双数据类型坐标的点创建一个类,这些是私有的。

为了练习运算符重载/基于成员函数的运算符对私有的访问,我编写了以下代码。

最后,我只想打印出两点坐标xy的相加结果。

我犯了什么错误?

提前感谢您的任何提示。

#include <stdio.h>
#include <iostream>

class point{
    
    public:
        // this operator adds a point "p2" to the point of class "point"
        // OVERLOADING BINARY + USING A MEMBER FUNCTION:
        point operator+(point p){ // n is the 2nd number in the addition
            return point(x+p.x, y+p.y); // equals (this->x+p2.x, ...)
        }
        
    // private numbers 
    private:
        //declaration and initialization of x and y:
        double x=1.1,y=2.2;
};

int main()
{
    // Create two new points:
    point *p1 = new point ();
    point *p2 = new point ();
    
    cout << "The result of the addition is: " << (*p1+*p2);
    
    return 0;
}

目前我得到的错误是:

In member function ‘point point::operator+(point)’: main.cpp:16:38:
error: no matching function for call to ‘point::point(double, double)’
return point(x+p.x, y+p.y); // equals (this->x+p2.x, ...)

【问题讨论】:

  • 这个错误基本上告诉你point没有一个需要2个双精度的构造函数。这是真的。 operator&lt;&lt; 也没有超载打印point。编译器不会为你做魔法;)

标签: c++ class overloading private operator-keyword


【解决方案1】:

就像 churill 指出的那样,您错过了两件事:

首先,您需要为您的点类实现一个构造函数,该构造函数需要 2 个双精度数:

point(double x, double y)
  : x(x), y(y)
{}

上面的构造函数使用initializer lists,和这个一样:

point(double x, double y) {
    this.x = x;
    this.y = y;
}

不要忘记再次实现默认构造函数,否则 C++ 将找不到它,您的代码将无法编译

point() {}

其次,您需要覆盖“

friend ostream& operator<<(ostream& os, const point& p) {
    os << "(" << p.x << ',' << p.y << ')'; // will output (x,y)
    return os;
}

如果您将上述所有内容作为 public 放在您的点类中,它应该可以毫无问题地编译

【讨论】:

  • 感谢您的提示,我确实学到了一些东西。其他问题: 1. 如果我离开默认构造函数会发生什么?
  • 2.据我了解,我不仅需要创建私有属性。我是否正确,您建议的构造函数行可以翻译成这样的原始语言:“获取私有属性 x,y(期望双精度),并使公开可用的 x 和 y 等于那些私有属性的值”?
  • 1.您的程序可能无法编译,因为它找不到您通过“point *p1 = new point ();”调用的默认构造函数
  • 2.构造函数只是将 x 和 y 传递给始终私有的属性。我在答案中添加了一个替代构造函数,这可能会使事情更清楚
  • 感谢您的详细解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
  • 2014-01-02
  • 2021-10-22
相关资源
最近更新 更多