如何拆分标头和重载实现运算符

how can I split the header and the Implementation by overloading operator

本文关键字:重载 实现 运算符 何拆分 拆分      更新时间:2023-10-16

正在学习C++来自Java世界的中级开发人员...

现在我正在尝试学习如何进行运算符重载

即使我在网上搜索了很多,所以:

如何正确重载 ostream 的 <<运算符?

https://stackoverflow.com/a/476483/982161

这是我的参考:

举这个例子:

// overload_date.cpp  
// compile with: /EHsc  
#include <iostream>  
using namespace std;  
class Date  
{  
    int mo, da, yr;  
public:  
    Date(int m, int d, int y)  
    {  
        mo = m; da = d; yr = y;  
    }  
    friend ostream& operator<<(ostream& os, const Date& dt);  
};  
ostream& operator<<(ostream& os, const Date& dt)  
{  
    os << dt.mo << '/' << dt.da << '/' << dt.yr;  
    return os;  
}  
int main()  
{  
    Date dt(5, 6, 92);  
    cout << dt;  
}  

但是我希望/需要使用标头和实现的分离来开发它

我的代码

页眉

#ifndef POINT_H
#define POINT_H
#include <ostream>
class Point
{
    public:
        Point();
        virtual ~Point();
        unsigned int Getx();
        unsigned int Gety();
        void Setx(unsigned int val);
        void Sety(unsigned int val);
        friend std::ostream& operator<<(std::ostream& ostream, const Point& dt);
    private:
        unsigned int x;
        unsigned int y;
};
#endif // POINT_H

实现

#include "Point.h"
#include <ostream>
Point::Point()
{
     x = 1u;
     y = 1u;
}
Point::~Point()
{
    //dtor
}
unsigned int Point::Getx()
{
     return x;
}
unsigned int Point::Gety()
{
    return y;
}
void Point::Setx(unsigned int val)
{
     x = val;
}
void Point::Sety(unsigned int val)
{
     y = val;
}
std::ostream& operator<<(std::ostream& out, const Point& a) {
    return out << "A(" << a.Getx() << ", " << a.Gety() ")";
}

我无法编译收到此错误的代码:

include\Point.h|24|error:将"const Point"作为"this"参数传递 'unsigned int Point::Getx((' 丢弃限定符 [-fpermissive]|

使代码编译的两件事:

第一:你的getter应该是恒定的。

unsigned int Getx() const;
unsigned int Gety() const;
unsigned int Point::Getx() const
{
   return x;
}
unsigned int Point::Gety() const
{
   return y;
}

第二:

更正被覆盖方法的返回:

return out << "A(" << a.Getx() << ", " << a.Gety() << ")";

(您错过了最后一个"<<"(。