1

通常、callBack() は Child クラスでオーバーライドする必要があります。

しかし、そうではありません。スレッドが callBack() を呼び出すと、元のメソッドが実行されます。

これを正す方法はありますか?

「g++ -o file source.cpp -lpthread」でコンパイルしました

私はそれがコンパイラに関するものではないと確信しています。

   #include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;

class Parent
{
    public:
        virtual void callBack()
        {
            cout << "Original callBack() reported this: " << this << endl;
        }
    private:
        pthread_t th = 0;

        static void *th_func(void *arg)
        {
            Parent *p = (Parent*)arg;
            cout << "*th_func() reported *arg: " << arg << endl;
            p->callBack();
        }
    public:
        Parent()
        {
            if(pthread_create(&th, NULL, th_func, (void*)this) < 0)
                cerr << "thread not born." << endl;
            else
                cout << "thread has born." << endl;
        }
        ~Parent()
        {
            if(th!=0)
                pthread_join(th, NULL);
            cout << "joined. Parent leaving." << endl;
        }
};

class Child : public Parent
{
    public:
        void callBack()
        {
            cout << "child overridden." << endl;
        }
        Child() : Parent(){}
};

int main()
{
    Child *ch = new Child();
    delete ch;
    return 0;
}
4

1 に答える 1