6.3 sizeof(5)

2013-10-07 14:09:05 · 作者: · 浏览: 57

6.3  sizeof(5)

答案:

正确的程序如下:

  1. #include <iostream> 
  2. #include <string> 
  3. using namespace std;  
  4.  
  5. int main(int argc,char *argv[])  
  6. {  
  7.     string strArr1[] = {"Trend",  
  8. "Micro","Soft"};  
  9.     string *pStrArr1 = new string[2];  
  10.     pStrArr1[0] = "US";  
  11.     pStrArr1[1] = "CN";  
  12.     cout << sizeof(strArr1) << endl;  
  13.     cout << sizeof(string) << endl;  
  14.     for(int i =0; i< sizeof(strArr1)/  
  15. sizeof(string);i++)  
  16.         cout << strArr1[i];  
  17.         cout << endl;  
  18.     for(int j =0; j< sizeof(*pStrArr1)*2/  
  19. sizeof(string);j++)  
  20.         cout << pStrArr1[j];  
  21.  
  22.     return 0;  
面试例题8:写出下面sizeof的答案。[德国某著名软件咨询企业2005年面试题]
  1. #include <iostream> 
  2. #include <complex> 
  3. using namespace std;  
  4. class Base  
  5. {  
  6. public:  
  7.    Base() { cout<<"Base-ctor"<<endl; }  
  8.    ~Base() { cout<<"Base-dtor"<<endl; }  
  9.    virtual void f(int) { cout<<"Base::  
  10. f(int)"<<endl; }  
  11.    virtual void f(double) {cout<<"Base::  
  12. f(double)"<<endl; }  
  13.    virtual void g(int i = 10) {cout<<"Base::  
  14. g()"<<i<<endl; }  
  15.    void g2(int i = 10) {cout<<"Base::  
  16. g2()"<<i<<endl; }  
  17. };  
  18.  
  19. class Derived: public Base  
  20. {  
  21. public:  
  22.    Derived() { cout<<"Derived-ctor"  
  23. <<endl; }  
  24.    ~Derived() { cout<<"Derived-dtor"  
  25. <<endl; }  
  26.    void f(complex<double>) { cout  
  27. <<"Derived::f(complex)"<<endl; }  
  28.    virtual void g(int i = 20) {cout  
  29. <<"Derived::g()"<<i<<endl; }  
  30. };  
  31.  
  32. int main()  
  33. {  
  34.   Base b;  
  35.   Derived d;  
  36.  
  37.   Base* pb = new Derived;  
  38.   //从下面的4个答案中选出1个正确的答案  
  39.   cout<<sizeof(Base)<<"tt"<<endl;  
  40.   //A.4    B.32    C.20  
  41. //D Platform-dependent  
  42.   cout<<sizeof(Derived)<<"bb"<<endl;  
  43.   //A.4    B.8 C.36    D.Platform-dependent  
  44.  

解析:求类base的大小。因为类base只有一个指针,所以类base的大小是4。Derive大小与base类似,所以也是4。

答案:A,A。

面试例题9:以下代码的输出结果是多少?[中国某著名计算机金融软件公司2006年面试题]

  1. char var[10]  
  2. int test(char var[])  
  3. {  
  4.   return sizeof(var)  
  5. }; 

A.10   B.9   C.11   D.4

解析:因为var[]等价于*var,已经退化成一个指针了,所以大小是4。

答案:D。