>>运算符重载插入?

Overloading insertion >> operator?

本文关键字:gt 插入 运算符 重载      更新时间:2023-10-16

我刚开始看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>>声明为自由函数。除此之外,代码看起来不错。

不能重载>>操作符作为成员函数,因为LinePoint在操作符的右侧。这绝对是一个愚蠢的理由,但这就是语法的本质。

当你进入类,这是更重要的,因为你的变量,如p1.x,将是private,你将不能把它们直接放入。

另外,您的const Line& line不应该是const,因为您正在通过输入它的变量来更改它!