C++比较两个对象
我得到了这个函数:
bool operator==(const foo& foo1, const foo& foo2)
如何比较两个对象,是否有库函数允许我这样做?或者我是否必须物理比较对象内的每个变量。
编辑:
foo
对象包含:
private:
int *values;
size_t *columns;
std::map< size_t, std::pair<size_t, unsigned int> > maps;
I got this function:
bool operator==(const foo& foo1, const foo& foo2)
how do I compare the two objects with each other, is there a library function that allows me to doit? or do I have to physically compare each of the variables inside the objects.
EDIT:
foo
object holds:
private:
int *values;
size_t *columns;
std::map< size_t, std::pair<size_t, unsigned int> > maps;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
比较函数的语义取决于您的意图以及对象内部的性质和语义。在您的情况下,只有您知道 foo 是什么,因此,只有您知道如何正确地将一个 foo 对象与另一个 foo 对象进行比较。对于您的问题,没有通用的一刀切的答案。
The semantics of the comparison function depends on your intent and in the nature and semantics of object's internals. In your case only you know what
foo
is and, therefore, only you know how to properly compare onefoo
object to anotherfoo
object. There's no universal one-fits-all answer to your question.你必须审视并比较自己内心的变量。
这样,您就可以定义什么是平等。如果
foo
代表一个人,您可以将两个foo
定义为相等,仅通过名字,或者通过名字和姓氏,或者通过社会安全号码,或者您所定义的任何内容。想。只有您,作为该类的作者,知道两个对象相等意味着什么。You have to go through and compare the variables inside yourself.
That way, you define what equality is. If
foo
represents a person, you can define twofoo
s as equal by just the first name, or by first and last name, or by social security number, or whatever you want. Only you, as the writer of the class, know what it means for two of your objects to be equal.它取决于类
foo
及其具有哪些数据成员,以及有效的相等性是什么。想象一下您的foo
如下:如果您想根据
id
字段进行比较:它们可以根据您的需要而简单或复杂。
It is dependant on the class
foo
and what data members it has, and what a vaild equality is. Imagine youfoo
is the following:If you wanted to compare based on the
id
field:They can be as simple or complicated as your needs require.
您拥有的重载运算符的签名适用于在 foo 类外部定义的静态函数。由于您声明
foo
的数据成员被声明为private
,因此您将很难让您的运算符正常工作。如果您需要在作业中使用该签名,则需要研究
friend
关键字...毕竟,它是作业,没有人会为您做。如果不是,请考虑使该运算符成为 foo 类的成员。 这是关于运算符重载的一个很好的一般参考。
The signature of the overloaded operator you have is for a static function defined outside of the
foo
class. Since you stated that the data members offoo
are declared asprivate
, you're going to have a tough time getting your operator to work.If you are required to use that signature for your homework, you need to research the
friend
keyword...after all, it is homework, nobody's going to do it for you.If not, consider making the operator a member of the
foo
class. This is a great general reference for operator overloading.