2013-04-14 144 views
0

這些都是我的類的屬性:結構在屬性

class Addition_Struct: public Addition { 
    // attributes 
    struct a { 
     int element; 
     struct a *next; 
    }; 
    struct b { 
     int element; 
     struct b *next; 
    }; 
    struct outcome { 
     int element; 
     struct outcome *next; 
    }; 
    struct a a_data; 
    struct b b_data; 
    struct outcome outcome_data; 
// methods 
a convertToStackA(int); // everything is right with this line 

我怎麼能叫他們從.cpp文件裏面?使用this->a語法返回「不允許輸入類型名稱」。使用a*作爲方法的返回值顯示「不允許標識符」,並且「聲明與...不兼容」。

.cpp文件:

a* Addition_Struct::convertToStackA(int number) 
{ 
    // identifier "a" is undefined, and declaration is incompatible 
} 
+0

我更新了我的答案,以解決您的新信息。見下圖。 – StoryTeller

回答

2

此:

class Addition_Struct: public Addition { 
// attributes 
    typedef struct a { 
     int element; 
     struct a *next; 
    } a; 
}; 

只定義了一個名爲Addition_Struct::a類型。沒有會員a,您可以通過this-a訪問。刪除typedef以獲得您想要的成員。

編輯

您提供的方法定義不在線(它的類定義之外)。因此,您必須使用完全範圍的類型名稱作爲返回類型。

Addition_Struct::a* Addition_Struct::convertToStackA(int number) 
{ 

} 

因爲編譯器看到類型Addition_Struct::a而不是類型a

0

在你例子中,你只申報結構,所以你Addition_Struct定義了3層結構,但沒有數據成員。你需要結構聲明後添加類似

a a_data; 
b b_data; 
outcome outcome_data; 

,才能夠訪問數據成員,如:

this->a_data; 
this->b_data; 
this->outcome_data; 
+0

是的,但是a_data等是指向第一個列表元素的指針。 – user2252786

1

從課堂內您可以使用a。從課外使用完全限定名Addition_Struct::a

順便說一句,因爲這是C++,你可以只使用

struct a { 
    int element; 
    a *next; 
}; 

沒有typedef的。

+1

+1用於評論typedef不是必需的。我非常理所當然地忘記提及它。 – StoryTeller

+0

那麼沒有辦法用「this」標識符來調用這個結構呢? – user2252786

+0

@ user2252786,而不是**類型名稱**'a'。如果你在該類中聲明瞭該類型的成員,那麼它當然可以通過'this'來訪問。 – StoryTeller