Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

pointers - C++ object equality

I have a class MyCloth and one one object instance of that class that I instantiated like this:

MyCloth** cloth1;

And at one point in the program, I will do something like this:

MyCloth** cloth2 = cloth1;

And then at some point later, I want to check to see if cloth1 and cloth2 are the same. (Something like object equality in Java, only here, MyCloth is a very complex class and I can''t build an isEqual function.)

How can I do this equality check? I was thinking maybe checking if they point to the same addresses. Is that a good idea? If so, how do I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can test for object identity by comparing the addresses held by two pointers. You mention Java; this is similar to testing that two references are equal.

MyCloth* pcloth1 = ...
MyCloth* pcloth2 = ...
if ( pcloth1 == pcloth2 ) {
    // Then both point at the same object.
}   

You can test for object equality by comparing the contents of two objects. In C++, this is usually done by defining operator==.

class MyCloth {
   friend bool operator== (MyCloth & lhs, MyCloth & rhs );
   ...
};

bool operator== ( MyCloth & lhs, MyCloth & rhs )
{
   return ...
}

With operator== defined, you can compare equality:

MyCloth cloth1 = ...
MyCloth cloth2 = ...
if ( cloth1 == cloth2 ) {
    // Then the two objects are considered to have equal values.
}   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...