https://blog.csdn.net/u012397189/article/details/78784928
默認構造函數
首先,我們來看一下是什么是默認構造函數,如下面一段代碼:
#include<iostream>
#include<math.h>
using namespace std;
class Point
{
double x, y;
public:
void print();
Point(double a=0,double b=1){x=a;y=b;} //默認構造函數
Point(double a){x=1;y=1;} //構造函數
Point(){} //默認構造函數
};
void Point::print()
{
cout << x << " " << y << endl;
}
所以,可以知道默認構造函數總得來說是可以在對象生成的時候,不需要傳入參數,對應情況就是:
Point point;
Point *point=new Point;
非默認構造函數就是必須要傳參。關於默認構造函數有以下知識點:
- 程序沒有定義任何構造函數,則有默認的構造函數Point(){},里面的成員的值沒有初始化
- 定義默認構造函數有兩種方式,如上述代碼展示的,一是定義一個無參的構造函數,二是定義所有參數都有默認值的構造函數
- 注意:一個類只能有一個默認構造函數!也就是說上述兩種方式不能同時出現,一般選擇 Point(); 這種形式的默認構造函數
帶默認構造函數的動態數組
我們來看一下如果一個類帶默認構造函數,如下代碼是生成靜態和動態數組的:
#include<iostream>
#include<math.h>
using namespace std;
class Point
{
double x, y;
public:
void print();
};
void Point::print()
{
cout << x << " " << y << endl;
}
int main() {
//靜態對象數組
Point pp[5];
for (int i = 0; i<5; i++)
pp[i].print();
//動態對象數組
Point *p = new Point[5]; //這里面5也可以是變量
for (int i = 0; i<5; i++)
p[i].print();
//別忘記delete相應的空間
}
可以看出來,如果一個類帶默認構造函數的話,那么生成的時候就不需要傳入參數了,方便了不少。
沒有默認構造函數的動態數組
如果一個類沒有默認構造函數呢,這種情況就需要傳入參數了,如下代碼:
#include<iostream>
#include<math.h>
using namespace std;
class Point
{
double x, y;
public:
Point(double a, double b);
void print();
};
Point::Point(double a, double b)
{
x = a;
y = b;
}
void Point::print()
{
cout << x << " " << y << endl;
}
int main()
{
Point *p[5];//靜態指針數組
for (int i = 0; i < 5; i++) {
p[i] = new Point(i, i); //其中你可以用自己的方式來初始化對象,例如從鍵盤接收值等
}
for (int i = 0; i < 5; i++) {
p[i]->print();
}
Point **pp = new Point *[5]; //動態指針數組,5也可以是變量
for (int i = 0; i < 5; i++) {
pp[i] = new Point(i, i);
}
for (int i = 0; i < 5; i++) {
pp[i]->print();
}
//別忘了delete相應的空間
return 0;
}
靜態指針數組是定義了一些的Point指針,通過new的方式來使每個指針指向對象。動態指針數組是分配固定大小的連續空間,里面的每個元素類型是Point *,然后把這連續空間的首地址給pp,pp是指向Point *類型的指針。
注意是 new Point *[5]而不是 new (Point *)[5],后者編譯器會報錯
new多維數組
int *p=new int[2];
int *p=new int[2][3]; //錯誤
int (*p)[3]=new int[2][3]; //正確
int (*p)[4][5]=new int[2][4][5]; //正確
為啥第二行就錯誤呢?其實我們可以這樣理解:
- int (*p)[3]其中p是指針,這是毋庸置疑的,那這個指針指向什么類的數據呢?
我們改一下寫法,編程int[3] (*p),是不是就很簡潔明了呢?p指向的類型是int[3]。
- new int[2][3]返回的2個int[3]類型的數組的首地址,賦值給p。
- 同理,第四行p指向的類型是int[4][5],new int[3][4][5]返回的是3個int[4][5]類型的數組的首地址,賦值給p。
- 針對第一行的情況,如果p的一開始地址為1000,假設int占用4個字節,那么執行p++以后,p的地址為1000+4,
第三行的情況,如果p的一開始地址為1000,進行p++以后,p的請值為1000+4*3,以此類推,第四行p++以后p的值為1000+4*4*5。