简体   繁体   中英

Implementing an interface in C++

How can I do this in C++

interface ActionListener { void actionPerformed(); }
jButton.addActionListener(
    new ActionListener(){ void actionPerformed() { do something } }
);

So far I know this,

class ActionListener {
  public : 
    virtual ~ActionListener(){}
    virtual void actionPerformed() = 0;
}

After this what do I do ... any keywords to do this kind of implemention would also help.

C++ doesn't really have anonymous classes like you find in Java. The usual thing is just to declare a subclass that inherits from the interface class. The closest you come to Java's anonymous class instance is something like this:

class : public ActionListener {
public:
    virtual void actionPerformed() {
        // do something
    }
} listener;
thing.addActionListener( listener );

There isn't much else to do in C++. You may want to use virtual inheritance when you implement, to avoid the diamond inheritance problem in case you eventually use multiple inheritance:

class SomeActionListener : virtual public ActionListener{
  public : 
    virtual ~ActionListener();
    virtual void actionPerformed();
}

In C++11, you can also use override for the method implementation. This checks at compile time in case you inadvertently mistyped the method name or got the cv qualifiers wrong, in which case you wouldn't be overriding:

class SomeActionListener : virtual public ActionListener{
  public : 
    virtual ~ActionListener();
    virtual void actionPerformed() override;
}

"How can I do this in C++?" -- It looks that what you are trying to do is to register a callback in a button. In C++, you do it in a different way: you do not need to provide any abstract class or an interface (in OO sense). Instead your button is likely to provide the following function for registering a callback:

void Button::addActionListener(std::function<void()> callback);

The type of callback is "any function, function pointer, or reference that can be called with zero arguments and returns nothing". Then you register your callback like this:

cppButton.addActionListener( [&]{ do something; } );
// lambda

Inherit from ActionListener .

C++ supports multiple inheritance. Java does not, so it must rely on interfaces.

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