Why is operator == not automatically synthesized for nested classes in C++

If I try to compile:

class Outer 
{
    class Inner 
    {
        int t;
    };
public:
    Inner inner_;
    bool operator ==(Outer rightSide);
};

bool Outer::operator ==(Outer rightSide)
{
    if (inner_ == rightSide.inner_)
        return true;
    return false;
}

I get an error:

/home/martin/Projects/Experimentation/Various-build-desktop/../Various/main.cpp:18: 
error: no match for ‘operator==’ in ‘((Outer*)this)->Outer::inner_ == 
rightSide.Outer::inner_’

Please, is it just me doing something wrong or is this a property of C++

EDIT:

Oh, I never realized that the operator == is never synthesized, I was so convinced that it is synthesized, that I did not bother to check.
Thank you Parapura Rajkumar!


Comparison operators are never implicitly generated. Only these things are:

  • Default constructor,
  • Destructor,
  • Copy and move constructors,
  • Copy-assigment and move-assignment operators
  • If you want to be able to compare your types, you'll have to write your own comparison operators. If you implement them as members, then they should be declared const ; otherwise, it will be impossible to compare constant objects. You might also consider taking arguments as constant references to avoid unnecessary copying; it makes little difference for simple types like these, but can be much more efficient for large or complicated classes. Something like:

    bool Outer::operator==(Outer const & rhs) const {
        return inner_.t == rhs.inner_.t;
    }
    

    or as a non-member function:

    bool operator==(Outer const & lhs, Outer const & rhs) {
        return lhs.inner_.t == rhs.inner_.t;
    }
    

    You didn't define the operator== for class Inner . So your code should be :

    class Outer
    {
        class Inner
        {
            int t;
        public:
            bool operator == (Inner inner)
            {
                return t == inner.t;
            }
        };
    public:
        Inner inner_;
        bool operator == (Outer rightSide);
    };
    
    bool Outer::operator == (Outer rightSide)
    {
        return inner_ == rightSide.inner_;
    }
    
    链接地址: http://www.djcxy.com/p/73776.html

    上一篇: 在C ++中没有重载operator ==的结构成员相等

    下一篇: 为什么operator ==不能自动为C ++中的嵌套类合成