C++ classes without .cpp files?

不问归期 提交于 2019-12-06 12:37:14

If some class doesn't need to be a template, don't make it a template just to "get rid of the linker's complains". Just use proper coding techniques, like providing inline defintions of member functions:

// log.hpp file

#pragma once

#include <iostream> // For std::cout, std::endl

class log {
private:
    static int m_cnt = 0;
public:
    log();
};

// Note "inline" here:
inline log::log() {
    std::cout << ++m_cnt << std::endl;
}

If you provide the function's body inside the class definition, then there's no need to specify the keyword inline:

// log.hpp file

#pragma once

#include <iostream> // For std::cout, std::endl

class log {
private:
    static int m_cnt = 0;
public:
    // Function body inserted here (no need for "inline"):
    log() {
        std::cout << ++m_cnt << std::endl;        
    }
};

As you want the functions to be defined in headers (which are included in multiple source files, which leads to multiple definitions in your case), you should make the functions inline.

2 options:

  • implicit inline - do not separate the function definitions
  • explicit inline - manually add inline keyword in front of the definitions

Using templates just to "work-around" this error is not a good idea. Use templates only when you need them.

WiSaGaN

What's wrong with this Method ? Is there something fundamentally wrong with this method ?

No, nothing is wrong with this method. What you need to do is to comply with One Definition Rule by doing:

  1. Make function definition inline by either putting the definition inside the declaration or by putting inline keyword before every function declaration. This is to avoid multiple definitions in multiple translation units (cpp files to simplify a little)
  2. Put include guards in the header files. This is to avoid multiple inclusion in the same translation unit.

Actually, this method is the only method for a template to work. You can't put the template definition in a cpp file, and expect it to work, because C++ compiler would need the definition to instantiate the template. Using template is not a solution for this method to work, but a mandate that requires you to only use this method if you want your code to compile.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!