关于运算符重载的问题

时间:2021-01-28 17:35:21

在设计类的时候,经常用到运算符的重载。运算符 operate<< 重载容易出问题。

常见的错误:

//vevtor.h

#include <iostream>

class vector{
private:
double x;
double y;
public:
……
std::ostream &operator<<(std::ostream &os, const vector &vec);
……
}

//vevtor.cpp

……
std::ostream &vector::operator<<(std::ostream &os, const vector &vec) {
std::cout << vec.x << "," << vec.y << std::endl;
}

编译是出现错误:

error:std::ostream& vector::operator<<(std::ostream&, const vector&)’ must take exactly one argument

错误的原因:

operator<<stream 的成员,不能写成自定义类成员。可定义成友员函数。

改正如下:

//vevtor.h

#include <iostream>

class vector{
private:
double x;
double y;
public:
……

frind std::ostream &operator<<(std::ostream &os, const vector &vec);

……
}

//vevtor.cpp

……

std::ostream &vector::operator<<(std::ostream &os, const vector &vec) {
std::cout << vec.x << "," << vec.y << std::endl;
return os;
}