1. 程式人生 > >C++復合類型(結構體)

C++復合類型(結構體)

iou .cn blog ges tor 例如 sig leon guests

其實c++的結構體可以理解為類似於python的字典,我個人理解, 但有區別

先看結構

#include <iostream>
關鍵字          標記成為新類型的名稱
struct          inflatable
{
    std::string mystr;                   結構成員
    char name[20];
    float volume;
    double price;
};

c++ 在聲明結構變量的時候可以省略關鍵字struct

同時還要註意外部聲明, 和局部聲明

技術分享
#include <iostream>
#include 
<string> #include <cstring> struct inflatable { std::string mystr; char name[20]; float volume; double price; }; int main(int argc, char const *argv[]) { using namespace std; inflatable guest = { "hello", "Glorious Gloria", 1.88,
29.99 }; inflatable pal = { "world", "Audacious Arthur", 3.12, 32.99 }; int a=12.40; std::cout << guest.mystr << \n; std::cout << a << \n; std::cout << "Expand your guest list with <<" << guest.name << ">>
" << "and" << "<<" << pal.name << ">>" << \n; std::cout << "you can have both for $" << guest.price + pal.price <<\n; return 0; }
View Code

其他結構屬性

#include <iostream>
#include <string>
#include <cstring>


struct inflatable
{
    std::string mystr;
    char name[20];
    float volume;
    double price;
};


int main(int argc, char const *argv[]) {
  using namespace std;
  inflatable guest = {
    "hello",
    "Glorious Gloria",
    1.88,
    29.99
  };
  inflatable choice = guest;   這種方法叫成員賦值
或者

inflatable choice;
choice = guest;

  std::cout << "Expand your guest list with <<" << guest.name << ">>" << \n;
  std::cout << "choice choice.mystr ---->" << choice.mystr << \n;
  return 0;
}

還可以

struct inflatable
{
    std::string mystr;
    char name[20];
    float volume;
    double price;
} mr_glitz = {"hello", "Glorious", 1.11, 11};
當然,也可以不賦值

結構數組

也可以創建元素為結構的數組, 方法和創建基本類型數組完全相同。例如:

#include <iostream>
#include <string>
#include <cstring>


struct inflatable
{
    std::string mystr;
    char name[20];
    float volume;
    double price;
} mr_glitz = {"hello", "Glorious", 1.11, 11};


int main(int argc, char const *argv[]) {
  using namespace std;

  inflatable guests[2] = {
    {"hello", "doman", 2.1, 2.22},
    // {"world", "corleone", 2.2, 3333}
  };
  std::cout << "guests[0].mystr: " << guests[0].mystr << \n;
  std::cout << "guests[1].name: " << guests[1].name << \n;

  return 0;
}

技術分享

結構中的位字段

  

struct torgle_register
{
  unsigned int SN :  4;
  unsigned int :4;
  bool goodIN : 1;
  bool goodTorgle : 1;
}

torgle_register tr = {14, true, false};

C++復合類型(結構體)