2014-03-19 148 views
0

如何訪問我的結構以在其中獲取/設置值? 這裏我的示例代碼如何在struct中設置/獲取struct結構中的值

#include <iostream> 
using namespace std; 
typedef struct t_TES 
{ 
    double dTes; 
}TES; 

struct SAMPLE1 
{ 
    struct TES; 
}; 

int main() 
{ 
    SAMPLE1 sss; 
    //How can i get/set dtes value?? 
    sss.TES.dtes=10; 
    cout<<sss.TES.dtes<<endl; 
    return 0; 
} 

是否更多鈔票像這樣「sss.TES.dtes = 10」分配值; 並通過調用這個「sss.TES.dtes」來獲取值; 我已經嘗試將 - >或::運算符組合起來以獲取/設置值,但總是遇到編譯錯誤。

原諒我的英語不好,謝謝..

+1

您的編譯器的錯誤消息應該顯示原因(錯誤:'struct SAMPLE1 :: TES'的無效使用)。閱讀它並看到你有一個TES嵌套結構。 –

回答

1

你有兩個問題SAMPLE1結構:第一個是你使用struct TESTES實際上不是一個結構(這是一個結構的別名 )。第二個問題是,你有實際聲明在SAMPLE1結構中的成員:

struct SAMPLE1 
{ 
    t_TES tes; 
}; 

然後你只需巢使用點操作.的(像你現在做的):

SAMPLE1 sss; 
sss.tes.dTes = 0.0; 
1

你不能。用struct TES;,你沒有聲明一個成員變量。嘗試TES member_name,那麼你可以通過sss.member_name訪問它。此外,您應該嘗試使用更多描述性變量名稱;-)

3

C++中的結構不需要typedefstruct關鍵字的實例,但它們確實需要其成員的名稱。此外,這是一種區分大小寫的語言,所以dtesdTes不一樣。嘗試:

#include <iostream> 
using namespace std; 

struct TES 
{ 
    double dTes; 
}; 

struct SAMPLE1 
{ 
    TES tes; 
}; 

int main() 
{ 
    SAMPLE1 sss; 
    sss.tes.dTes = 10; 
    cout << sss.tes.dTes << endl; 
    return 0; 
}