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
409 views
in Technique[技术] by (71.8m points)

c++ - Assignment operator not available in derived class

The assignment operator in base class does not seem to be available in derived class. Given this code:

#include <iostream>

class A{
    int value;
public:
    A& operator=(int value){
        this->value = value;
        return *this;
    }
};

class B : public A{};

int main(){
    B b;
    b = 0; // Does not work
    return 0;
}

GCC 6.4 says:

error: no match for 'operator=' (operand types are 'B' and 'int')

What is happening?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Every class has at least one assignment operator implicitly defined when we don't provide one ourselves.

And when a member function in a derived class is defined with the same name as a member in the base class, it hides all the base class definitions for that name.

You can use a using declaration, but be warned that it will pull all the members named operator= and allow code like this:

A a;
B b;
b = a;

Which is slightly dubious.


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

...