gpt4 book ai didi

c++ - 函数比较器可以是静态函数吗?

转载 作者:行者123 更新时间:2023-11-30 04:11:56 24 4
gpt4 key购买 nike

我已经为 Point2D 类实现了两个运算符重载

  1. operator<
  2. operator>

在头文件中,我需要声明为友元函数,否则会出现编译错误。
问题:运算符重载函数总是友元函数吗?可以是静态的吗?我尝试使用静态函数,但出现错误:

Point2D.h:19:58: error: ‘static bool Point2D::operator<(const Point2D&, const Point2D&)’ must be either a non-static member function or a non-member function
In file included from Point2D.cpp:3:0:
Point2D.h:19:58: error: ‘static bool Point2D::operator<(const Point2D&, const Point2D&)’ must be either a non-static member function or a non-member function
Point2D.h: In function ‘bool operator<(const Point2D&, const Point2D&)’:
Point2D.h:23:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:36:11: error: within this context
Point2D.h:24:7: error: ‘int Point2D::y’ is protected
Point2D.cpp:36:17: error: within this context

class Point2D
{

friend ostream &operator<<( ostream &output, const Point2D &P);
friend bool operator<(const Point2D& A, const Point2D& B);
friend bool operator>(const Point2D& A, const Point2D& B);

protected:
int x;
int y;
public:
//Constructor
Point2D();
Point2D (int x, int y);

//Accessors
int getX();
int getY();

//Mutators
void setX (int x);
void setY (int y);
};


ostream &operator<<( ostream &output, const Point2D &P)
{
output << "X : " << P.x << "Y : " << P.y;
return output;
}

bool operator<(const Point2D& A, const Point2D& B )
{
return A.x < B.y;
};


bool operator>(const Point2D& A, const Point2D& B )
{
return A.x > B.y;
};

最佳答案

二元运算符可以作为全局二元函数或一元成员函数来实现。在后者中,运算符的第一个操作数被隐式传递(是 *this,在所有成员函数中):

选项1:全局函数

struct foo
{
int a;
};

bool operator==( const foo& lhs , const foo& rhs )
{
return lhs.a == rhs.b;
}

方案二:成员函数

struct foo
{
int a;

bool operator==( const foo& rhs )
{
// +---- this->a
// |
// v
return a == rhs.a;
}
};

选项3:类内部的全局函数,声明为友元(我的最爱)

struct foo
{
int a;

friend bool operator==( const foo& lhs , const foo& rhs )
{
return lhs.a == rhs.b;
}
};

有关运算符重载的完整而深入的指南,请查看此 C++ wiki 线程:Operator overloading

关于c++ - 函数比较器可以是静态函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20021808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com