2017-02-24 88 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流輸出操作人員可以訪問它們。

相關問題