>>运算符重载插入?
Overloading insertion >> operator?
我刚开始看c++中的结构体,我想我可能会尝试找出如何重载流插入操作符来获取Line的对象(它本身包含Point的对象)。我想我需要在Line中声明重载?还有点吗?我发现了一些类似的问题,但老实说,我一点也想不出来。
这是一个非常简单的程序,所以希望有人能花时间看看它,并向我解释我应该怎么做?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::istream;
//define Point & Line type
struct Point{
float x, y;
};
struct Line{
Point p1, p2;
istream& operator>>( istream& in, const Line& line); //something like this here?
};
//function declarations
Point calcMidpoint(const Line& rline);
//operator overload
istream& operator>>( istream& in, const Line& line){
in >> line.p1.x >> line.p1.y >> line.p2.x >> line.p2.y;
return in;
}
//MAIN
int main(){
Line line;
cout << "please enter one pair of x and y values followed by another like so (x1 y1 x2 y2): ";
cin >> line;
//get midpoint of line
Point mp;
mp = returnMidpoint(line);
cout << "The Midpoint is.. (" << mp.x << " " << mp.y << ")" <<endl;
return 0;
}
//can be used in a large expression at the expence of creating temp instances
Point calcMidpoint(const Line& rline){
Point midpoint;
midpoint.x = (rline.p2.x + rline.p1.x) / 2;
midpoint.y = (rline.p2.y + rline.p1.y) / 2;
return midpoint;
}
只有当第一个操作数是类的类型时,二元操作符才能定义为成员函数。由于情况并非如此(第一个操作数是std::istream&
),您必须定义一个自由的函数:
class Foo;
std::istream & operator>>(std::istream & is, Foo & x)
{
//...
return is;
}
在类中声明此函数为friend
可能会有用,以便它可以访问私有成员。
您需要将operator>>
声明为自由函数。除此之外,代码看起来不错。
不能重载>>
操作符作为成员函数,因为Line
和Point
在操作符的右侧。这绝对是一个愚蠢的理由,但这就是语法的本质。
当你进入类,这是更重要的,因为你的变量,如p1.x
,将是private
,你将不能把它们直接放入。
另外,您的const Line& line
不应该是const
,因为您正在通过输入它的变量来更改它!
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何将结构插入到集合中并打印集合的成员
- C++json插入数组
- Visual Studio 2019:插入多个C++风格的单行注释
- nlohmann-json将一个数组插入到另一个数组中
- 有效地使用std::unordered_map来插入或增加键的值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 正在插入动态数组
- 插入或删除时获取usb的dos_name
- EASTL矢量<向量<int>>连续的
- 叮叮当当在修复时插入多个"覆盖"说明符
- 链表c++插入,所有情况都已检查,但没有任何工作
- 将重物插入std::map
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 在数字之间插入 + 或 - 符号以使其等于整数
- 在字符串中插入空格