Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

oop - Copy assignment operator for diamond inheritance C++

I have 4 classes in a diamond inheritance hierarchy. Is it right to call both parents' assignment operator for the assignment operator in der12 class? Wouldn't it call the base operator= 2 times? Is there a better way to do it?

    protected:
        int a = 1;

    public:
        base& operator=(const base& ref){
            ...
        }
};

class der1 : virtual public base{
    protected:
        int b = 2;
    
    public:
        der1& operator=(const der1& ref){
            ...
        }
};

class der2 : virtual public base{
    protected:
        int c = 3;
        
    public:
        der2& operator=(const der2& ref){
            ...
        }
};

class der12 : public der1, public der2{
    int d = 4;

    public:
        der12& operator=(const der12& ref){
            der1::operator=(ref);
            der2::operator=(ref);
            d = ref.d;
            
            return *this;
        }
};```

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

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...