重载插入>>运算符?

Hol*_*lly 3 c++ struct input

我刚刚开始在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;
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 6

如果第一个操作数属于类的类型,则二进制运算符只能定义为成员函数.由于不是这种情况(第一个操作数是std::istream&),您必须定义一个自由函数:

class Foo;

std::istream & operator>>(std::istream & is, Foo & x)
{
  //...
  return is;
}
Run Code Online (Sandbox Code Playgroud)

friend在类中声明此函数可能很有用,因此它可以访问私有成员.

  • @holly:他只是意味着一个普通的函数,它不是某个类的方法. (2认同)
  • @Holly:自由函数是一个不是成员函数的函数.这意味着它在一个类之外声明. (2认同)