pure virtual function and abstract class

前端 未结 2 365
挽巷
挽巷 2021-01-25 07:58

I have the following classes, Base and Derived and when I compile the compiler complains that it cannot create an instance of DLog because it is abstract.

Can someone te

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-25 08:23

    virtual void log(string logText, int debugLevel, string threadName = "") = 0;
    

    has not been implemented in class DLog. You have to implement it because it's pure virtual in the base class.

    You probably meant this in your first overload of log in DLog:

    virtual void log(string logText, int debugLevel, string /*threadname*/)
    {
        Log(const_cast(logText.c_str()));
    }
    

    EDIT: You also have not implemented the overload of

    virtual void log(int debugLevel, char* fmt, ...) = 0;
    

    Note here though that using the const_cast is a very bad idea and is undefined behavior. You can get well defined behavior by doing something like this instead:

    virtual void log(string logText, int debugLevel, string /*threadname*/)
    {
        logText.push_back('\0'); // Add null terminator
        Log(&logText[0]); // Send non-const string to function
        logText.pop_back(); // Remove null terminator
    }
    

    Better yet though, just make "Log" const-correct in the first place.

提交回复
热议问题