简体   繁体   中英

Override virtual method from abstract class

I need to test notifying system based on observer pattern. Here is my Observer class:

template <typename DataType>
class Subject;

template <typename DataType>
class Observer {
public:
    virtual ~Observer() {}
    virtual void receive(Subject<DataType> *subject) = 0;
};

DataType is tparam data. receive() will receive and process the message called by Subject when it is updated. Subject is a pointer to the subject from which the data came.

Here is a part of Subject class with attach() method:

template <typename DataType>
class Subject {
public:
    typedef Observer<DataType> SameDataObserver;

    Subject():
        dataPtr_(NULL),
        observers_() {
    }

    void attach(SameDataObserver *observerPtr) {
        assert(observerPtr != NULL);
        observers_.pushBack(observerPtr);
    }
...
private:
...
};

So, I wrote an inheritor of the Observer abstract class like this. I guess here I need to define only the receive() method:

class TestObserver : Observer<IdString> {
    virtual void receive(Subject<DataType> *subject) override {};
};

IdString is typedef String<64> IdString; .

In my main() function, I do this:

const IdString data = "button pressed";
Subject<IdString> subject;
TestObserver<IdString> testObserver;
subject.attach(&testObserver);

Here is the error that I get:

[build] /home/a.wise/Downloads/test_notifying_system/test_notifying_system.cpp:20:32: error: no matching function for call to ‘Subject<String<64> >::attach(TestObserver<String<64> >&)’
[build]      subject.attach(testObserver);
[build]                                 ^
[build] In file included from /home/a.wise/Downloads/test_notifying_system/test_notifying_system.cpp:7:0:
[build] /home/a.wise/Downloads/test_notifying_system/src/notifying_system/subject.h:29:10: note: candidate: void Subject<DataType>::attach(Subject<DataType>::SameDataObserver*) [with DataType = String<64>; Subject<DataType>::SameDataObserver = Observer<String<64> >]
[build]      void attach(SameDataObserver *observerPtr) {
[build]           ^~~~~~

I missed public word, right code:

template <typename DataType>
class TestObserver : public Observer<IdString> {
    public:
    virtual void receive(Subject<DataType> *subject) override {};
};

After that it compiles

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