簡體   English   中英

靜態類成員,它是一個結構體

[英]Static class member, which is a struct

我有一個類,我想要一個靜態成員,它是一個結構體。

例如:.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 成員),用靜態成員方法操作它,並在代碼的其他幾個部分中包含這個頭文件。 這應該用於通過應用程序添加日志記錄。

您需要在 cpp 文件中初始化您的靜態成員:

//add the following line:
TransactionLog CTransactionLog::logInfo;

void CTransactionLog::Clear()
{
    logInfo.Reference = "";
    logInfo.CreditLog.clear();
 logInfo.id = 0;
}

TransactionLog CTransactionLog::getLog()
{
    return logInfo;
}

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

文件

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

主文件

#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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM