如何拆分标头和重载实现运算符
how can I split the header and the Implementation by overloading operator
正在学习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() << ")";
(您错过了最后一个"<<"(。
相关文章:
- 如何为我的类实现/重载二进制运算符
- 如何为非常量和常量重载实现一次成员函数?
- 基于 SFINAE 的特征实现问题与函数模板重载
- 在函数重载中将右值引用实现为参数
- 如何实现容器的重载和模板函数的迭代器?
- 我想知道我将如何实现 + 运算符重载.我已经从我上一个问题中计算出 += 运算符重载
- 给定一个类型为 Container:<T>:Iterator 的函数参数,如何为某些类型的 T 实现特定的重载?
- C++ I/O 流重载:如何实现同一标头中相同 4 个 I/O 函数的 3 个不同类的友元重载?
- C++头/实现文件中的默认和重载构造函数?
- 为模板类中的>>运算符和<<运算符实现重载
- 什么更有效率?在重载函数中或通过在基类函数中检查对象类型来实现
- 将多态性与运算符 + 重载模板化类结合使用.如何实现基类?
- 如何拆分标头和重载实现运算符
- 通过重载实现部分模板专用化
- 重载实现的虚拟函数
- C++ - 使用取消引用运算符重载实现图形节点的合并
- 为什么运算符重载实现中的两个 Static 对象在 c++ 中始终相等
- 通过运算符重载实现矩阵乘法
- 运算符重载实现:0xC0000005:读取位置存在访问冲突
- c++中迭代器的前缀和后缀自增操作符重载实现的区别