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位版本。 –