struct 結構名稱{
資料型態 資料成員1
資料型態 資料成員2
資料型態 資料成員3
...
函數型態 成員函數1(參數型態 虛擬參數1, ....){
...
...
}
函數型態 成員函數2(參數型態 虛擬參數1, ....){
...
...
}
};
struct parent
{
string name;
int age;
};
struct employee
{
int id;
string name;
struct parent myparent;
};
注意
定義巢狀結構時候,單層結構定義要寫在雙層結構定義上面,雙層結構定義要寫三層結構定義上面。否則會出現類似field 結構名稱 'has incomplete type'的錯誤訊息。
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
struct tel_book{
string name;
int age;
string tel;
void printdata(void){
cout<< name <<'\t'
<< age <<'\t'
<< tel <<endl;
}
};
struct tel_book telephone[3]={
{"John",28,"04-2302"},
{"Kate",23,"06-3402"},
{"Issac",30,"04-8216"},
};
struct tel_book temp;
cout<< " Data before sorting... " << endl;
for(int i= 0 ; i < 3 ;i++)
telephone[i].printdata();
for(int i=1 ;i <=2;i++){
for(int j=0;j<3-i;j++){
if(telephone[j].age > telephone[j+1].age){
temp = telephone[j];
telephone[j] = telephone[j+1];
telephone[j+1]=temp;
}
}
}
cout<< " Data After sorting... " << endl;
for(int i= 0 ; i < 3 ;i++)
telephone[i].printdata();
return 0;
}
enum 列舉名稱
{
成員名稱 1[=資料1],
成員名稱 2[=資料2],
...
}
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
enum Is_Use{
yes,
no
};
std::istream& operator>>( std::istream& is, Is_Use& i )
{
int tmp ;
if ( is >> tmp )
i = static_cast<Is_Use>( tmp ) ;
return is ;
}
int main(int argc, char const *argv[])
{
enum Is_Use use;
cin >> use;
if(use==yes){
cout << use <<": Yes";
}
if(use==no){
cout << use<<": No";
}
return 0;
}
std::istream& operator>>( std::istream& is, Is_Use& i )
{
int tmp ;
if ( is >> tmp )
i = static_cast<Is_Use>( tmp ) ;
return is ;
}