哪个派生类对象在基类中称为非虚函数

时间:2018-12-18 14:07:53

标签: c++ derived-class base-class

背景

我有一个基类 Base ,它具有主要个“纯”虚拟功能和一些非虚拟功能(以及几个虚拟功能)。

>

基本上,所有派生类 Derived Derived2 等中的通用功能在基类中均以非虚拟功能存在。

问题: 如果来自任何派生类的对象之一调用了基类中的任何非虚函数,那么如何(如果有的话)就可以知道哪个派生类对象调用了该非虚基类功能。

实际上,我想调试一个调用,但偶然发现,无论是使用调试器还是使用任何跟踪线,我都无法确定我是从哪个派生类对象中发现这个非虚拟基类函数的事实

想想看,当我写这个问题时,我可以想到的一种方法是,我可以在每个派生类中都有一个静态成员字符串变量,并将其作为参数传递给非虚拟基类函数。但是,那是唯一的方法吗?

最低工作示例: 这是最小的工作示例。我尽可能地将其剥离。

#include <iostream>


#include <pthread.h>
#include <string>
#include <errno.h>
#include <cstring>

class Base {
public:
    Base() {}
    virtual ~Base() {}
    int waitForThreadToExit() {
        int error = pthread_join(m_Thread, NULL);
        if (0 != error) {
            std::cerr << "Error from pthread_join(). errorCode:" << strerror(errno) << std::endl;
        }
        return error;
    }

    int start() {
        if ((startThread()) != 0) {
             std::cerr << "error returned from the start() function." << std::endl;
         }
    }

protected:
    virtual int runThread(void) {
      std::cout << "Reimplement" << std::endl;;
      return -1;
    }
    int startThread() {
        int error = pthread_create(&m_Thread, NULL, internalThreadEntryFunc, this);
        return error;
    }

private:
    static void* internalThreadEntryFunc(void* This) {
        ((Base *) This)->runThread();
        return NULL;
    }
    pthread_t m_Thread;
};


class Derived: public Base {
public:
    Derived() {}
    virtual ~Derived() {}

private:
    virtual int runThread(void) {
        while(1) {
             std::cout << "Sehr gut!" << std::endl;;
             return 0;
        }
    }

};

class Derived2: public Base {
public:
    Derived2() {}
    virtual ~Derived2() {}

private:
    virtual int runThread(void) {
        while (1)
        {
            std::cout << "Sehr sehr gut!" << std::endl;;
            return 0;
        }
    }

};


int main()
{
    std::cout << "Hello World!" << std::endl;
    Derived d;
    Derived2 d2;
    d.start();
    d2.start();
    d.waitForThreadToExit();
    d2.waitForThreadToExit();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

因此,为了完整起见,以防万一其他人(可能几个月后我很可能自己)再次遇到这个问题,这是我为解决此问题而实施的一般想法。

#include <iostream>
#include <typeinfo>

class base {
public:
    virtual const char* name() {
        return typeid(*this).name();
    }
    virtual ~base(){}
};

class derived : public base {};
class otherDerived : public base {};

int main () {
    base b;
    derived d;
    otherDerived d2;

    std::cout << "base says:" << b.name() << std::endl;
    std::cout << "derived says:" << d.name() << std::endl;
    std::cout << "other derived says:" << d2.name() << std::endl;
}

在我的QtCreator中运行时提供输出:

  

base说:4base
  派生说:7dervied
  其他派生说:12otherDerived

注意:最好制作一个虚函数name()className()并在各处调用该函数,而不要在代码中各处撒上typeid(*this).name()。 / p>

相关问题