开发者

c++ compare object

开发者 https://www.devze.com 2023-02-24 16:45 出处:网络
I want to compare to objects to see if they are the same in C++. If 开发者_JAVA技巧I do it in C# it would look like this:

I want to compare to objects to see if they are the same in C++.

If 开发者_JAVA技巧I do it in C# it would look like this:

object result = human.find();
if (result == Human.NotFound) 
{ return ...

How would I do this in C++?

[edit] C++ code:

Class HumanFamily : public std::map <ExString, Human> {
public:
   static const Human NoHumanFound;
const Human Find (const ExString& name ) const {
  HumanFamily::const_iterator it = find (name);
  if (it == this->end()) {
     return NoHumanFound;
}
return (it->second);
}

Class calling the above method:

Object r = HumanFamily.begin()->Find (name);
if (r == HumanFamily.NoHumanFound) {
  return HumanFamily.NoHumanFound;

}

return r;


The C++ language does not have the concept of object, a class that acts as base class for all classes. With that in mind and assuming that you have a Human class, you would need to define the operator == for the class. One way to do that is:

class Human {
public:
    bool operator ==(Human const& ) const;
    /* ... */
};

and then later:

bool are_they_the_same(Human const& human1, Human const& human2)
{
    return human1 == human2;
}


The C# code is actually comparing addresses - are those two references to the same object, rather than whether those two objects have an equal value.

You should not overload operator== in C++ with the same meaning. In C++ it means checking whether two, possibly distinct objects have the same value. E.g a and b could be different strings both containing "Hello world" and hence a==b would be true.

Your particular code

Object r = HumanFamily.begin()->Find (name);
if (r == HumanFamily.NoHumanFound) {
  return HumanFamily.NoHumanFound;

}

return r;

most likely involves slicing (the static and dynamic type of r will be Object), and could be just replaced with

return HumanFamily.begin()->Find (name);


This is pretty terrible. You should not inherit from Standard classes (except iostreams) because they do not have virtual destructors- especially when it could just be replaced by composition. In addition, the std::map already has a NotFound value- std::map<>::end();. On top of that, your functions serve no purpose, and it looks to me like you're trying to return polymorphically but actually it's not a reference, it's a value.

You need to get a book on the C++ and actually understand it, because this code makes me think that you seriously need the help.

Hell, you just need to get a book about programming in general. That usage function you posted could be just replaced with return HumanFamily.begin()->Find(name);.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号