array地址问题(为何指向赋值,仍然地址不同)

来源:互联网 发布:bf是什么软件 编辑:程序博客网 时间:2024/06/06 02:52

代码quote:c++ primer plus ----  example 4.24

#include <iostream>
#include <vector>
#include <array>

int main(int argc, const char * argv[]) {
// insert code here...

using namespace std;

double a1[4] = {1.2, 2.4, 3.6, 4.8};
vector<double> a2(4);
a2[0] = 1.0/3.0;
a2[1] = 1.0/5.0;
a2[2] = 1.0/7.0;
a2[3] = 1.0/9.0;

array<double, 4> a3 = {3.14, 2.72, 1.62, 1.41};
array<double, 4> a4;
a4 = a3;

cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl;
cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl;
cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;

a1[-2] = 20.2;
cout << " a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl;
cout << " a3[2]: " << a3[2] << " at " << &a3[2] << endl;
cout << " a4[2]: " << a4[2] << " at " << &a4[2] << endl;

return 0;
}

计算机结果

a1[2]: 3.6 at 0x7fff5fbff7f0

a2[2]: 0.142857 at 0x100105520

a3[2]: 1.62 at 0x7fff5fbff648

a4[2]: 1.62 at 0x7fff5fbff628

a1[-2]: 20.2 at 0x7fff5fbff7d0

a3[2]: 1.62 at 0x7fff5fbff648

a4[2]: 1.62 at 0x7fff5fbff628

Program ended with exit code: 0


编译环境:mac os, xcode 7.1.1


为何array a4 指向 array a3,地址不同。

猜想:c++重载了 = , 当a4 = a3的时候,识别类别array,进行赋值操作,因而指针可以不同,在array<type , n_element>的时候已经初始化了


http://stackoverflow.com/questions/34459937/how-class-array-workc-does-it-get-a-memory-while-declaration?noredirect=1#comment56662812_34459937


0 0
原创粉丝点击