2017-02-24 92 views
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 . . . 
+0

通常情况下,第一个printf会导致运行时错误。顺便说一句,compiller应该给出相应的警告。 – dmi

+1

你的假设是错误的。第一个'printf'不能像你期望的那样工作。 (它将对象p放入堆栈,然后将第一个'sizeof(int)'字节作为int值读取。)'printf'确实使用可变参数并且**不是**类型安全的。改用'std :: cout'来代替。那么,它可能甚至不会编译。 (因为'sample'类没有输出操作符。) – Scheff

+0

不,我没有收到任何编译器错误。我已经粘贴了终端的输出。顺便说一下,我使用的是dev C++,编译器是TDM-GCC 4.9.2 64位版本。 –

回答

4

printf使用可变参数。虽然,我在gcc中看到扩展来检查对照格式字符串的可变参数,但实际上没有真正的编译时间检查格式字符串的参数类型匹配。因此,printf不应该在C++中使用。类型安全的替代品是流。

流操作符(实际上是过载移位操作符)可用于内置类型以及标准库的某些类(例如std::string)。

为了支持自设计类的流输出,流输出操作符必须为它重载。例如: -

#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; 
} 

编译和测试GCC在Cygwin:

$ g++ -std=c++11 -o test-cout test-cout.cc 

$ ./test-cout 
sample: 123, 234, 345 

我的确让a, b, cprivate证明,如果做了friend流输出操作人员可以访问它们。

相关问题