2013-07-08 130 views
2

数组我很困惑与cplusplus.com类型变量的对象

// pointer to classes example 
#include <iostream> 
using namespace std; 

class CRectangle { 
    int width, height; 
    public: 
    void set_values (int, int); 
    int area (void) {return (width * height);} 
}; 

void CRectangle::set_values (int a, int b) { 
    width = a; 
    height = b; 
} 

int main() { 
    CRectangle a, *b, *c; 
    CRectangle * d = new CRectangle[2]; 
    b= new CRectangle; 
    c= &a; 
    a.set_values (1,2); 
    b->set_values (3,4); 
    d->set_values (5,6); 
    d[1].set_values (7,8); 
    cout << "a area: " << a.area() << endl; 
    cout << "*b area: " << b->area() << endl; 
    cout << "*c area: " << c->area() << endl; 
    cout << "d[0] area: " << d[0].area() << endl; 
    cout << "d[1] area: " << d[1].area() << endl; 
    delete[] d; 
    delete b; 
    return 0; 
} 

我在想采取为什么d[0].area()是合法的,而不是d[0]->area(),这导致我的d减速下面的例子其中CRectangle * d = new CRectangle[2];。是不是有两个级别的间接,所以不应该dCRectangle ** d宣布,因为新返回一个指针,它是一个指针,因为它是一个数组(因此是[])。换句话说不是**=*[]

+6

不,**阵列不是指针!** – chris

+2

请勿使用cplusplus.com,请使用[cppreference](http://en.cppreference.com/w/) – Borgleader

+0

[您需要了解的所有数组](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) – Praetorian

回答

1

为:

CRectangle *d = new CRectangle[2]; 

(大致)相当于(永远,永远,永远做到这一点,只需使用新):

CRectangle *d = (CRectangle*)malloc(2*sizeof(CRectangle)); 
... plus some default construction ... 

d是一个指针。 d [0]不是指针,它是数组索引0处的值。

d [n]是*(d + n)的简写形式,它是数组中位置'n'的值(因此为取消引用*) d。 new CRectangle[2]的返回值是CRectangle*

数组存储在存储器中,如:

 
     d[0] [1] [2] [3] [4] [5] [6] [7] ... 
Value A B C D E F G H ... 
offset: 0 +1 +2 +3 +4 +5 (x sizeof(CRectangle) of course)...
+0

除了我相信'malloc'是UB。 – chris

+0

new相当于malloc和一个构造函数调用 - 在这种情况下,默认的构造函数。 – Joel

+0

@Joel,但是你不能'malloc'非POD类型(或者可以,但是不应该除非你喜欢有不可预测的代码)。 – chris

2

CRectangle * d = new CRectangle[2];声明d作为指针以CRectangle并对其进行初始化,以指向含有两个CRectangle对象的数组的第一个对象。所以d[0],具有类型CRectangle,而不是指向CRectangle的指针。这就是为什么使用点运算符(。)是合法的。

+0

很迂腐:作为一个对象是存储区域,我认为数组*的短语*元素比数组*的对象稍好。该标准在[expr.new]/5中使用短语“初始元素”。 – dyp

+0

@DyP希望我当前的编辑更好地强调,我指的是'd [0]'的类型,这是我在OO意义上使用单词“object”的初始意图。 –

+0

你的回答很好,很好,我只是做了一个很迂腐的评论;)+1 – dyp