The C Programming Language 的第 2.3.2 章列出了這個建構式:
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} { }
private:
double* elem;
int sz;
};
據我所知,陣列大小必須是一個常量運算式,而s不是。這合法嗎?如果是這樣,為什么?
uj5u.com熱心網友回復:
是的,這是合法的,因為陣列是在運行時使用“new”運算子分配的。
如果要在編譯時分配陣列,則必須提供 const int 或常量運算式。
int count = 0;
cin >> count;
int* a = new int[count]; // This is dynamic allocation happen at runtime.
int b[6]; // This is static allocation and it happen at compile-time.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429310.html
標籤:C
