没有.cpp文件的C ++类? [英] C++ classes without .cpp files?

查看:260
本文介绍了没有.cpp文件的C ++类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想为每个简单的c ++类写一个 .cpp 文件。

I don't want to write a .cpp file for every simple c++ class.

在单个 .hpp 文件中写入类定义和声明,
链接器声明关于成员函数的多重定义,这些成员函数没有在类的正文中实现。

when I write a class definition and declaration in a single .hpp file, the linker complains about multiple definition of member functions which are not implemented inside the body of the class.

因此我使用模板来摆脱链接器投诉:

So I use templates to get rid of linker complaints:

// log.hpp file
template<typename T>
class log_t {
private:
    int m_cnt = 0;
public:
    void log();
};

template<typename T>
void log_t<T>::log() {
    std::cout << ++m_cnt << std::endl;
}

// some random type (int)
typedef log_t<int> log;

然后我可以使用 log class在多个 .cpp 文件中没有链接器投诉。

And then I can simply use log class in multiple .cpp files without linker complaints.

这个方法有根本上错误吗?

Is there something fundamentally wrong with this method?

编辑:即使我使用这个方法会使成员函数内联吗?

even when i use this method will member functions become inline ?

推荐答案

如果某个类不需要是模板,那么不要使它成为仅用于摆脱链接器的抱怨。只需使用正确的编码技术,例如提供成员函数的内联定义:

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;
}

如果你在类定义中提供函数的body,那么就不需要指定关键字 inline

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;        
    }
};

这篇关于没有.cpp文件的C ++类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆