2016-04-15 78 views
-2

將Struct作爲參數傳遞給函數時出現問題。我已經定義了結構爲:結構作爲函數的參數

struct message{ 
    static unsigned int last_id; 
    unsigned int id; 
    std::string msg; 
    std::string timestamp; 
    message(void) 
    { 
    } 
    message(const std::string& recvbuf_msg,const std::string& a_timestamp) : 
    msg(recvbuf_msg), timestamp(a_timestamp), id(++last_id) 
    { 
    } 
}; 

和函數定義是這樣的:

void print_msg(message *myMsg,std::string recv_usrn){ 
    cout << "#" << myMsg->id << " @" << recv_usrn << ": " << myMsg->msg << " at " << myMsg->timestamp << endl; 
} 

在主我已經使用了功能類似這樣:

message myMsg; 
string recv_usrn; 
print_msg(&myMsg,recv_usrn); 

而且問題是它給出了這些錯誤:

C2065:消息:未聲明的標識符

C2065:myMsg':未聲明的標識符

C2182: 'print_msg':我非法使用類型 '空隙'

+3

你忘了包括聲明o f'消息'?請發佈[MCVE]。 –

+0

當我寫'message myMsg'時,只是明確說明'myMsg'是一個消息類型的圖形。它之前在代碼中填充。 – 19mike95

+0

要使用'message'結構,您必須先定義它。它是否在print_msg函數的定義(實現)之前定義?在調用'print_msg'之前定義'myMsg'變量之前定義了結構? –

回答

3

的它正在工作,你把每一件事在同一個文件.. 這是工作正常

#include <iostream> 
#include <cstdio> 
using namespace std; 
struct message{ 
    static unsigned int last_id; 
    unsigned int id; 
    std::string msg; 
    std::string timestamp; 
    message(void) 
    { 
    } 
    message(const std::string& recvbuf_msg,const std::string& a_timestamp) : 
    msg(recvbuf_msg), timestamp(a_timestamp), id(++last_id) 
    { 
    } 
}; 

void print_msg(message *myMsg,std::string recv_usrn){ 
    cout << "#" << myMsg->id << " @" << recv_usrn << ": " << myMsg->msg << " at " << myMsg->timestamp << endl; 
} 

int main() 
{ 
message myMsg; 
string recv_usrn; 
print_msg(&myMsg,recv_usrn); 
}