我有以下问题。在下面的代码中,对象变量p的地址与其第一个成员'a'的地址相同。但是当我打印p和a的值时,它们都是。为什么同一地址位置有两个不同的值?
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 . . .
答案 0 :(得分:4)
printf
使用可变参数。虽然,我看到gcc中的扩展来检查格式字符串的可变参数,实际上没有真正的编译时间检查格式字符串的参数的类型匹配。
因此,不应在C ++中使用printf
。类型安全的替代方案是流。
流操作符(实际上这些是重载的移位操作符)可用于内置类型以及标准库的某些类(例如std::string
)。
为了支持自行设计类的流输出,必须为它输出流输出操作符。 E.g:
#include <iostream>
class Sample {
friend std::ostream& operator << (std::ostream&, const Sample&);
private:
int _a, _b, _c;
public:
Sample(int a, int b, int c): _a(a), _b(b), _c(c) { }
};
std::ostream& operator << (std::ostream &out, const Sample &s)
{
return out << s._a << ", " << s._b << ", " << s._c;
}
int main(int, char**)
{
Sample sample = Sample(123, 234, 345);
std::cout << "sample: " << sample << std::endl;
return 0;
}
在cygwin上使用gcc进行编译和测试:
$ g++ -std=c++11 -o test-cout test-cout.cc
$ ./test-cout
sample: 123, 234, 345
我确实要a, b, c
private
来证明如果设为friend
,流输出操作员可以访问它们。