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

时间:2017-04-04 11:15:34

标签: c++ operator-overloading

我正在学习来自java世界的 C ++ 作为中档开发人员...

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

甚至我在网上搜索了很多东西并且SO:

How to properly overload the << operator for an ostream?

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

here是我的参考:

举个例子:

// 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] |

1 个答案:

答案 0 :(得分:0)

使代码编译的两件事:

第一: 你的吸气剂应该是常量。

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() << ")";

(你错过了最后一个“&lt;&lt;”)。