C++ 中的聯合體



在 C++ 中,**聯合體 (union)** 是一種使用者定義的資料型別,允許您在同一記憶體位置儲存不同的資料型別。但是,聯合體一次只能儲存其一個成員變數,這意味著如果您為一個成員賦值,則之前儲存在另一個成員中的值將被覆蓋。其中聯合體的大小由其最大成員的大小決定。

聯合體宣告

要宣告一個聯合體,請使用**union**關鍵字後跟**tag_name**(聯合體名稱),然後在花括號內宣告聯合體成員及其資料型別。用分號結束宣告。

以下是宣告聯合體的語法:

union UnionName {
  dataType1 member1;
  dataType2 member2;
  // more members
};

示例

這是一個基於上述語法宣告聯合體的簡短示例:

union UnionName {
  int intValue;     // Member for integer value
  float floatValue; // Member for float value
  char charValue;   // Member for character value
};

宣告聯合體變數

宣告聯合體後,您需要宣告其變數以訪問和操作其成員。

以下是宣告聯合體變數的語法:

union_name variable;

訪問聯合體成員

您可以使用點運算子 (.) 在宣告聯合體變數後訪問聯合體成員。

以下是訪問聯合體成員的語法:

union_variable.member

C++ 聯合體示例

這是一個聯合體的完整示例,演示了它的工作原理:

#include <iostream>
#include <cstring>

using namespace std;

union Data {
  int intValue; // Member for integer value
  float floatValue; // Member for float value
  char strValue[50]; // Member for string value
};

int main() {
  // Defining a union variable
  Data data;

  data.intValue = 2006;
  cout << "TutorialsPoint: Founded in " << data.intValue << endl;

  // overwrites the previous integer value
  data.floatValue = 5.75f;
  cout << "My Float value is: " << data.floatValue << endl;

  // overwrites the previous float value
  strcpy(data.strValue, "Hello TutorialsPoint Learner");
  cout << data.strValue << endl;

  // Accessing the integer after assigning a string
  cout << "Integer after string assignment: " << data.intValue << endl;
  // Undefined behavior

  return 0;
}

當以上程式碼編譯並執行時,會產生以下結果:

TutorialsPoint: Founded in 2006
My Float value is: 5.75
Hello TutorialsPoint Learner
Integer after string assignment: 1819043144

解釋

以上示例演示了聯合體的用法,如何建立和訪問它。

  • 首先,定義了一個名為**Data**的聯合體,它包含三個成員:**int intValue, float floatValue, char strValue[50]**,其中任何時候只能有一個成員持有值。
  • 由於聯合體的大小由最大成員決定,因此在本例中(字元陣列)。
  • 在 int main() 函式體中聲明瞭一個聯合體變數**data**。
  • 要分配和訪問成員,所有成員都使用“.” 分別分配其值,如**data.intValue**。
  • 對於浮點值,浮點成員**floatValue**被賦值為 5.75。
  • 但是,由於聯合體一次只能儲存一個值,因此**intValue** 的先前值被覆蓋,儘管它仍然會佔用相同的記憶體空間。
  • 現在最後,當代碼嘗試在字串賦值覆蓋後列印**intValue** 時。這會導致**未定義行為**,整數值不再有效,訪問它可能會產生意外的結果,如輸出所示。

匿名聯合體

匿名聯合體是一種特殊的聯合體,它沒有名稱。這有助於透過允許您直接訪問聯合體成員而無需指定聯合體變數名稱來簡化程式碼。

語法

這是一個匿名聯合體的簡單語法,它在宣告時沒有名稱,允許直接訪問其成員:

union {
  dataType1 member1;
  dataType2 member2;
  // additional members...
};

示例

這是一個基於上述語法的匿名聯合體示例:

#include <iostream>

#include <cstring>

using namespace std; // Use the standard namespace

int main() {
  // Anonymous union declaration
  union {
    int intValue;
    float floatValue;
    char strValue[50];
  };

  // Assigning an integer value
  intValue = 2006;
  cout << "Integer Value: " << intValue << endl;

  // Assigning a float value (overwrites the previous integer value)
  floatValue = 3.14 f;
  cout << "Float Value: " << floatValue << endl;

  // Assigning a string value (overwrites the previous float value)
  strcpy(strValue, "Hello, TutorialsPoint Learner!");
  cout << "String Value: " << strValue << endl;

  // Accessing the integer after string assignment (undefined behavior)
  cout << "Integer after string assignment: " << intValue << endl;

  return 0;
}

當以上程式碼編譯並執行時,會產生以下結果:

Integer Value: 2006
Float Value: 3.14
String Value: Hello, TutorialsPoint Learner!
Integer after string assignment: 1819043144

類似聯合體的類

在 C++ 中,**類似聯合體的類**定義為包含至少一個匿名聯合體作為成員的類。在這些匿名聯合體中定義的資料成員稱為變體成員。它是封裝聯合體概念但提供型別安全性和可用性的額外功能的資料結構。

這些通常結合使用成員變數和機制(如列舉器)來跟蹤當前活動型別。

語法

這是一個類似聯合體的類的基本語法,其中使用**class**關鍵字定義類,後跟類名(此處為 UnionLikeClass)

class UnionLikeClass {
public:
  union {
    dataType1 member1;  // Member of type dataType1
    dataType2 member2;  // Member of type dataType2
    // additional members...
  };
};

示例

這是一個基於上述語法的類似聯合體的類示例

#include <iostream>

#include <cstring>

using namespace std;

class UnionLikeClass {
  public:
    // Anonymous union declaration
    union {
      int intValue; // Member for integer value
      float floatValue; // Member for float value
      char strValue[50]; // Member for string value
    };

  // Method to display the current value
  void display() {
    cout << "Integer Value: " << intValue << endl;
    cout << "Float Value: " << floatValue << endl;
    cout << "String Value: " << strValue << endl;
  }
};

int main() {

  // Creating an instance of UnionLikeClass
  UnionLikeClass data;

  data.intValue = 2006;
  cout << "TutorialsPoint: Founded in " << data.intValue << endl;

  data.floatValue = 3.14f;
  cout << "Assigned Float Value: " << data.floatValue << endl;

  // Assigning a string value (overwrites the previous float value)
  strcpy(data.strValue, "Hello, Union Like Class!");
  cout << "Assigned String Value: " << data.strValue << endl;

  // Accessing the integer after string assignment (undefined behavior)
  cout << "Integer after string assignment: " << data.intValue << endl;
  // Undefined behavior

  return 0;
}
TutorialsPoint: Founded in 2006
Assigned Float Value: 3.14
Assigned String Value: Hello, Union Like Class!
Integer after string assignment: 1819043144
廣告