简体   繁体   中英

Inline inheritance of an abstract class in C++

In Java, we can inherit an interface inside a method like that:

public Class myClass {
    void myMethod() {
        myInterface listener = new myInterface() {
            public onClick() {
                //code goes here
            }
        };
        setListener(listener);
    }
}

In C++; assuming I have an abstract class:

class myInterface {
    public:
        myInterface();
        virtual ~myInterface() {};
        virtual void onClick() = 0;
}

I try to inline inherit this abstract class like below but it gives errors:

myClass::myMethod() {
    myInterface *listener;
    listener = new myInterface() {
        virtual void onClick() {
            //some code here
        }
    };
    setListener(listener);
    delete listener;
}

All of the examples and tutorials I find on internet explain inheritance via subclassing. But how I can inline inherit this abstract class inside myClass::myMethod()?

The short answer is: you cannot.

There is no secret keyword or compiler feature you missed.

C++ is not Java. There are different patterns, idioms and syntactic tricks the C++ people use to achieve the same effect. You will need to read a good book or tutorial to get them.

You can use the C++ way:

include

#include <boost/signals2.hpp>

class notifier {
public:
  void notify(int i) {
    handlers(i);
  }
  boost::signals2::connection add_listener(std::function<void(int)> listener) {
   return handlers.connect(std::move(listener));
  }
  void remove_listener(boost::signals2::connection &connection) {
    handlers.disconnect(connection);
  }
private:
  boost::signals2::signal<void(int)> handlers;
};
...
notifier n;
n.add_listener([](int i) {
  std::cout << i << std::endl;
});
n.notify(100);

If you're using C++11 you can adopt lambdas for that:

class myLambdaListener : public myInterface{
    public:
        myLambdaListener(const std::function<void()>& func) : mFunction(func){}
        void onClick() override {if(mFunction) mFunction();}
    private:
    std::function<void()> mFunction;
}

myClass::myMethod() {
    myInterface *listener;
    listener = new myLambdaListener([](){
            //some code here
    });
    setListener(listener);
    //delete listener; - do not delete here
}

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