静态类成员,它是一个结构体
我有一个类,我想在其中有一个静态成员,它是一个结构。
例如: .h 文件:
typedef struct _TransactionLog
{
string Reference;
vector<int> CreditLog;
int id;
}TransactionLog;
class CTransactionLog {
static TransactionLog logInfo;
public:
static void Clear();
static TransactionLog getLog();
};
.cpp 文件:
void CTransactionLog::Clear()
{
logInfo.Reference = "";
logInfo.CreditLog.clear();
logInfo.id = 0;
}
TransactionLog CTransactionLog::getLog()
{
return logInfo;
}
我明白了
描述资源路径位置类型
对“CTransactionLog::logInfo”TransactionLog.cpp 的未定义引用
有人能给我一个如何实现此功能的示例吗?拥有一个结构体静态成员(带有 stl 成员),使用静态成员方法对其进行操作,并将此标头包含在代码的其他部分中。这应该用于通过应用程序添加日志记录。
I have a class in which I would like to have a static member which is a struct.
for example:
.h file:
typedef struct _TransactionLog
{
string Reference;
vector<int> CreditLog;
int id;
}TransactionLog;
class CTransactionLog {
static TransactionLog logInfo;
public:
static void Clear();
static TransactionLog getLog();
};
.cpp file:
void CTransactionLog::Clear()
{
logInfo.Reference = "";
logInfo.CreditLog.clear();
logInfo.id = 0;
}
TransactionLog CTransactionLog::getLog()
{
return logInfo;
}
I get
Description Resource Path Location Type
undefined reference to `CTransactionLog::logInfo' TransactionLog.cpp
Can someone please give me an example how to make this work? Having a static member which is a struct(with stl members), manipulate it with static member methods and include this header in few other parts of the code. This should be used to add logging through the application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(2)
我是 C/C++ 新手,我使用 Arduino IDE 构建了它,抱歉。 struts可以在类内部,为了返回结构,它必须是公共的,如果想法只是返回值,请将其构建为私有的。
foo.h
class CTransactionLog
{
public:
struct TransactionLog
{
int id;
};
static void Clear();
static CTransactionLog::TransactionLog getLog();
static int getId();
private:
static CTransactionLog::TransactionLog _log_info;
};
foo.cpp
#include "foo.h"
CTransactionLog::TransactionLog CTransactionLog::_log_info;
void CTransactionLog::Clear()
{
_log_info.id = 0;
}
CTransactionLog::TransactionLog CTransactionLog::getLog()
{
return _log_info;
}
int CTransactionLog::getId()
{
return _log_info.id;
}
main.ino
#include "foo.h"
void setup()
{
Serial.begin(115200);
CTransactionLog::Clear();
CTransactionLog::TransactionLog log = CTransactionLog::getLog();
int id = CTransactionLog::getId();
Serial.println(log.id);
Serial.println(id);
}
void loop()
{
}
输出:
0
0
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您需要在 cpp 文件中初始化静态成员:
You need to initialize your static member in the cpp file: