3
我有以下問題。在下面的代碼中,對象變量p的地址與其第一個成員'a'的地址相同。但是,當我打印p的價值和他們都是。相同的地址位置如何保存兩個不同的值?同一地址位置如何給出兩個不同的值?
class sample {
public:
int a;
int b;
int c;
//sample();
sample(int x,int y, int z){
a=x;
b=y;
c=z;
}
};
int main() {
//sample p;
//sample sample(2,3,4);
sample p = sample(2,3,4);
// cout<<"The value that is stored in the z is "<< p <<endl;
printf("The value of the object handle p is %d \n",p);
printf("The address of the object handle p is %d \n",&p);
//p->a =2;
//p->b =3; This could be accessesd in the later part of the code.
//p->c =4;
printf("The address of a is %d\n",&(p.a));
printf("The value stored in the a is %d\n",p.a);
printf("The value stored in the b is %d\n",p.b);
printf("The value stored in the c is %d\n",p.c);
}
上述代碼的輸出是:
The value of the object handle p is 2358832
The address of the object handle p is 2358848
The address of a is 2358848
The value stored in the a is 2
The value stored in the b is 2358852
The value stored in the c is 2358856
--------------------------------
Process exited after 0.2105 seconds with return value 0
Press any key to continue . . .
通常情況下,第一個printf會導致運行時錯誤。順便說一句,compiller應該給出相應的警告。 – dmi
你的假設是錯誤的。第一個'printf'不能像你期望的那樣工作。 (它將對象p放入堆棧,然後將第一個'sizeof(int)'字節作爲int值讀取。)'printf'確實使用可變參數並且**不是**類型安全的。改用'std :: cout'來代替。那麼,它可能甚至不會編譯。 (因爲'sample'類沒有輸出操作符。) – Scheff
不,我沒有收到任何編譯器錯誤。我已經粘貼了終端的輸出。順便說一下,我使用的是dev C++,編譯器是TDM-GCC 4.9.2 64位版本。 –