2014-11-03 66 views
-2

例如:c + +:如何糾正傳輸數組字符串到函數?

#include <stdio.h> 
#include <string.h> 

using namespace std; 

struct st 
{ 
    string name[3]; 
    st(char X[][]) { for(int i=0; i<3; i++) name[i] = X[i];} 
} Y({"Text1", "Text2", "Text3"}); 

但Y({ 「文本1」, 「文本2」, 「文本3」})沒有工作。而我不知道正確的答案。請幫助。

這工作正常。

struct st 
    { 
     string name; 
     st(char X[]) { name[i] = X;} 
    } Y("Text1"); 
+2

廢話。首先閱讀一些介紹性的C++ **書**。不問問題只是爲了提問。先學習基礎知識,做一些練習,然後問問你是否面臨解決練習的任何問題。 – Nawaz 2014-11-03 18:19:07

回答

0
結構

使用C++ 11

struct st 
{ 
    array<string, 3> name; 
    st(const array<string, 3>& name) 
     : name(name) 
    { 
    } 
}; 

int main() 
{ 
    st s({ "Text1", "Text2", "Text3" }); 
    cout << s.name[0] << endl; 
} 

直播示例 http://ideone.com/cxMNnX

1

如果要評論錯誤的成員函數聲明並用大括號代替括號,那麼代碼將被編譯。 :)

struct st 
    { 
     std::string name[3]; 
//   std(char X[][]) { for(int i=0; i<3; i++) name[i] = X[i];} 
    } Y { {"Text1", "Text2", "Text3"} }; 

至於成員函數(看來你要定義構造函數),那麼它可能會像

st(const char *s[3]) 
{ 
    for (size_t i = 0; i < 3; i++) name[i] = s[i]; 
} 

被定義或者你可以這樣定義

struct st 
{ 
    std::string name[3]; 
    st(std::initializer_list<const char *> l) 
    { 
     size_t n = std::min<size_t>(3, l.size()); 
     std::copy_n(l.begin(), n, name); 
    } 
} Y ({"Text1", "Text2", "Text3" }); 
+0

這僅僅是一個例子。構造函數有很多參數,那麼如何? – Archont 2014-11-03 18:29:04

+0

@Archont查看我更新的帖子 – 2014-11-03 18:40:50

+0

上面的解決方案較爲複雜,不過感謝您的幫助。 – Archont 2014-11-03 20:46:47