简体   繁体   中英

Compare two objects of the same type for equality without public getters?

I have a class with several members. I've so far successfully had no getters in my class which I like because I don't want people exposing the specifics of the class. I then had to compare two objects of this class for equality. I can't think of a way around creating several public getters. I really don't want to do this to keep encapsulation. Is there another way?

class Foo
{
public:
    bool Equals( const Foo &other ) const;
private:
    bool x;
    // lots of other members
};

bool Foo::Equals( const Foo &other ) const
{
    // would I have to create and use public function other.GetX()?
}

You can create your own public equality member operator:

class Foo
{
    public:
        bool operator ==(Foo const& rhs) const
        {
            return x == rhs.x;
        }
};

Example of use:

Foo a, b;

assert(a == b);

@0x499602D2 has already given a good answer that explains how to do this.

To add to that, I think the key point you haven't picked up yet is that access specifiers ( protected and private ) apply at the class level, not the instance level. So one instance of a class can access private members of another instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM