詳解C++編程中數組的根本用法。本站提示廣大學習愛好者:(詳解C++編程中數組的根本用法)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解C++編程中數組的根本用法正文
可使用數組下標操作符 ([ ]) 拜訪數組的各個元素。 假如在無下標表達式中應用一維數組,組名盤算為指向該數組中的第一個元素的指針。
// using_arrays.cpp
int main() {
char chArray[10];
char *pch = chArray; // Evaluates to a pointer to the first element.
char ch = chArray[0]; // Evaluates to the value of the first element.
ch = chArray[3]; // Evaluates to the value of the fourth element.
}
應用多維數組時,在表達式中應用各類組合。
// using_arrays_2.cpp
// compile with: /EHsc /W1
#include <iostream>
using namespace std;
int main() {
double multi[4][4][3]; // Declare the array.
double (*p2multi)[3];
double (*p1multi);
cout << multi[3][2][2] << "\n"; // C4700 Use three subscripts.
p2multi = multi[3]; // Make p2multi point to
// fourth "plane" of multi.
p1multi = multi[3][2]; // Make p1multi point to
// fourth plane, third row
// of multi.
}
在後面的代碼中, multi 是類型 double 的一個三維數組。 p2multi 指針指向年夜小為三的 double 類型數組。 本例中該數組用於一個,兩個和三個下標。 雖然指定一切下標更加罕見(如 cout 語句所示),然則以下的語句 cout 所示,有時其在選擇數組元素的特定子集時異常有效。
初始化數組
假如類具有結構函數,該類的數組將由結構函數初始化。假如初始值設定項列表中的項少於數組中的元素,則默許的結構函數將用於殘剩元素。假如沒無為類界說默許結構函數,初始值設定項列表必需完全,即數組中的每一個元素都必需有一個初始值設定項。
斟酌界說了兩個結構函數的Point 類:
// initializing_arrays1.cpp
class Point
{
public:
Point() // Default constructor.
{
}
Point( int, int ) // Construct from two ints
{
}
};
// An array of Point objects can be declared as follows:
Point aPoint[3] = {
Point( 3, 3 ) // Use int, int constructor.
};
int main()
{
}
aPoint 的第一個元素是應用結構函數 Point( int, int ) 結構的;殘剩的兩個元素是應用默許結構函數結構的。
靜態成員數組(能否為 const)可在其界說中停止初始化(類聲明的內部)。例如:
// initializing_arrays2.cpp
class WindowColors
{
public:
static const char *rgszWindowPartList[7];
};
const char *WindowColors::rgszWindowPartList[7] = {
"Active Title Bar", "Inactive Title Bar", "Title Bar Text",
"Menu Bar", "Menu Bar Text", "Window Background", "Frame" };
int main()
{
}
表達式中的數組
當數組類型的標識符湧現在 sizeof、address-of (&) 或援用的初始化之外的表達式中時,該標識符將轉換為指向第一個數組元素的指針。 例如:
char szError1[] = "Error: Disk drive not ready."; char *psz = szError1;
指針 psz 指向數組 szError1 的第一個元素。 請留意,與指針分歧,數組不是可修正的左值。 是以,以下賦值長短法的:
szError1 = psz;