c++面試題(13)

來源:互聯網
上載者:User

1.下面的代碼輸出是什麼,為什嗎?
       void foo(void)
       {
            unsigned int a = 6;
            int b = -20;
            (a+b>6)?puts(">6"):puts("<=6");//puts為列印函數
       }
答:輸出 >6.就是考察隱式轉換.int型變數轉化成unsigned int, b成了正數.

2. 運行下面的函數會有什麼結果?為什嗎?//有點象華為的試題
       void foo(void)
          {
               char string[10],str1[10];
               int i;
               for(i=0;i<10;i++)
               {
                    str1[i] = 'a';
               }
               strcpy(string, str1);
           printf("%s",string);
          }

答:首先搞清strcpy函數的實現方法:

char * strcpy(char * strDest,const char * strSrc)
{
  if ((strDest == NULL) || (strSrc == NULL)) 
    throw "Invalid argument(s)";
  char * strDestCopy = strDest; 
  while ((*strDest++ = *strSrc++) != '/0'); 
  return strDestCopy;
}

由於str1末尾沒有‘/0’結束標誌,所以strcpy不知道拷貝到何時結束.
printf函數,對於輸出char* 類型,順序列印字串中的字元直到遇到Null 字元('\0')或已列印了由精度指定的字元數為止.

3. Implement a string class in C++ with basic functionality like comparison, concatenation, input and output. Please also provide some test cases and using scenarios (sample code of using this class).

Please do not use MFC, STL and other libraries in your implementation.

我的實現方案如下,這道題真地對c++的主要特性都進行了較好地考察.

String.h:

#ifndef STRING_H
#define STRING_H

#include <iostream>
using namespace std;

class String{
   public:
    String();
       String(int n,char c);
    String(const char* source);
    String(const String& s);
    //String& operator=(char* s);
    String& operator=(const String& s);
    ~String();

    char& operator[](int i){return a[i];}
    const char& operator[](int i) const {return a[i];}//對常量的索引.
    String& operator+=(const String& s);
    int length();

   friend istream& operator>>(istream& is, String& s);//搞清為什麼將>>設定為友元函數的原因.
   //friend bool operator< (const String& left,const String& right);
   friend bool operator> (const String& left, const String& right);//下面三個運算子都沒必要設成友元函數,這裡是為了簡單.
   friend bool operator== (const String& left, const String& right);
   friend bool operator!= (const String& left, const String& right);
   private:
    char* a;
    int size;
};

#endif

String.cpp:

#include "String.h"
#include <cstring>
#include <cstdlib>

String::String(){
    a = new char[1];
    a[0] = '/0';
    size = 0;
}

String::String(int n,char c){
 a = new char[n + 1];
 memset(a,c,n);
 a[n] = '/0';
 size = n;
}

String::String(const char* source){
 if(source == NULL){
  a = new char[1];
  a[0] = '/0';
  size = 0;
 }
 else
 {   size = strlen(source);
  a = new char[size + 1];
  strcpy(a,source);
 }
}

String::String(const String& s){
 size = strlen(s.a);//可以訪問私人變數.
 a = new char[size + 1];
 //if(a == NULL)
 strcpy(a,s.a);
}

 

String& String::operator=(const String& s){
 if(this == &s)
  return *this;
 else
 {
  delete[] a;
        size = strlen(s.a);
  a = new char[size + 1];
  strcpy(a,s.a);
  return *this;
 }
}
String::~String(){
 delete[] a;//    
}

String& String::operator+=(const String& s){
  int j = strlen(a);
  int size = j + strlen(s.a);
  char* tmp = new char[size+1];
  strcpy(tmp,a);
  strcpy(tmp+j,s.a);
 delete[] a;
 a = tmp;

 return *this;
 }

int String::length(){
 return strlen(a);
}

main.cpp:

#include <iostream>
#include "String.h"

using namespace std;

bool operator==(const String& left, const String& right)
{
 int a = strcmp(left.a,right.a);
    if(a == 0)
  return true;
 else
  return false;
}
bool operator!=(const String& left, const String& right)
{
 return  !(left == right);
}

ostream& operator<<(ostream& os,String& s){
 int length = s.length();
 for(int i = 0;i < length;i++)
  //os << s.a[i];這麼不行,私人變數.
  os << s[i];
 return os;
}

String operator+(const String& a,const String& b){
 String temp;
 temp = a;
 temp += b;
 return temp;

}

bool operator<(const String& left,const String& right){
 
 int j = 0;
 while((left[j] != '/0') && (right[j] != '/0')){
  if(left[j] < right[j])
   return true;
  else
  {
   if(left[j] == right[j]){
    j++;
    continue;
   }
   else
    return false;
  }
 }
 if((left[j] == '/0') && (right[j] != '/0'))
  return true;
 else
  return false;
}

bool operator>(const String& left, const String& right)
{   int a = strcmp(left.a,right.a);
    if(a > 0)
  return true;
 else
  return false;
 
}

istream& operator>>(istream& is, String& s){
 delete[] s.a;
 s.a = new char[20];
 int m = 20;
    char c;
 int i = 0;
 while (is.get(c) && isspace(c));
    if (is) {
  do {s.a[i] = c;
       i++;
    /*if(i >= 20){
      cout << "Input too much characters!" << endl;
      exit(-1);
    }*/
    if(i == m - 1 ){
     s.a[i] = '/0';
     char* b = new char[m];
     strcpy(b,s.a);
                 m = m * 2;
        s.a = new char[m];
     strcpy(s.a,b);
     delete[] b;
    }
  }
  while (is.get(c) && !isspace(c));
        //如果讀到空白,將其放回.
  if (is)
   is.unget();
 }
 s.size = i;
 s.a[i] = '/0';
 return is;
}

int main(){
 String a = "abcd";
 String b = "www";
 //String c(6,b);這麼寫不對.
    String c(6,'l');
 String d;
 String e = a;//abcd
 String f;
 cin >> f;//需要輸入...
 String g;
 g = a + b;//abcdwww

 if(a < b)
  cout << "a < b" << endl;
 else
  cout << "a >= b" << endl;
 if(e == a)
  cout << "e == a" << endl;
 else
  cout << "e != a" << endl;
 
 b += a;
 
 cout << a << endl;
 cout << b << endl;
    cout << c << endl;
 cout << d << endl;
 cout << e << endl;
 cout << f << endl;
 cout << g << endl;
 cout << g[0] << endl;
 return 0;
}

 

 

4. Implement a single-direction linked list sorting algorithm. Please first define the data structure of linked list and then implement the sorting algorithm.

 

5.編寫一個函數,返回兩個字串的最大公串!例如,“adbccadebbca”和“edabccadece”,返回“ccade”

 

1.設計函數 int atoi(char *s)。

 int atoi(const char *nptr);
 函數說明
 atoi()會掃描參數nptr字串,跳過前面空白字元,直到遇上數字或正負符號才開始做轉換,而再 遇到非數字或字串結束時('/0')才結束轉換,並將結果返回。
傳回值 返迴轉換後整型數。

#include <stdio.h>
#include <ctype.h>

int myAtoi(const char* s){
 int result = 0;
 int flag = 1;
 int i = 0;
 while(isspace(s[i]))
  i++;
 if(s[i] == '-'){
  flag = -1;
  i++;
 }
 if(s[i] == '+')
  i++;
 while(s[i] != '/0'){
  if((s[i] > '9') || (s[i] < '0'))
   break;
  int j = s[i] - '0';
  result = 10 * result + j;
  i++;
 }
 result = result * flag;
 return result;
}

int main(){
 char* a = "   -1234def";
 char* b = "+1234";
 int i = myAtoi(a);
 int j = myAtoi(b);
 printf("%d /n",i);
 printf("%d",j);
 return 0;
}

 
 

 
2.int i=(j=4,k=8,l=16,m=32); printf(“%d”, i); 輸出是多少?

7.下列哪兩個是等同的
  int b;
  A const int* a = &b;
  B const* int a = &b;
  C const int* const a = &b;
  D int const* const a = &b;

8.內嵌函式在編譯時間是否做參數類型檢查?
  void g(base & b){
   b.play;
  }
  void main(){
   son s;
   g(s);
   return;
  }

1.完成下列程式
  *
  *.*.
  *..*..*..
  *...*...*...*...
  *....*....*....*....*....
  *.....*.....*.....*.....*.....*.....
  *......*......*......*......*......*......*......
  *.......*.......*.......*.......*.......*.......*.......*.......
  #include <stdio.h>
  #define N 8
  int main()
  {
   int i;
   int j;
   int k;
   ---------------------------------------------------------
   | |
   | |
   | |
   ---------------------------------------------------------
   return 0;
  }

2.完成程式,實現對數組的降序排序
  #include <stdio.h>
  void sort( );
  int main()
  {
   int array[]={45,56,76,234,1,34,23,2,3}; //數字任//意給出
   sort( );
   return 0;
  }
  void sort( )
  {
   ____________________________________
   | |
   | |
   |-----------------------------------------------------|
  }

3.費波那其數列,1,1,2,3,5……編寫程式求第十項。可以用遞迴,也可以用其他方法,但要說明你選擇的理由。
  #include <stdio.h>
  int Pheponatch(int);
  int main()
  {
   printf("The 10th is %d",Pheponatch(10));
   return 0;
  }
  int Pheponatch(int N)
  {
  --------------------------------
  | |
  | |
  --------------------------------
  }

 

4.下列程式運行時會崩潰,請找出錯誤並改正,並且說明原因。
  #include <stdio.h>
  #include <malloc.h>
  typedef struct{
   TNode* left;
   TNode* right;
   int value;
  } TNode;
  TNode* root=NULL;
  void append(int N);
  int main()
  {
   append(63);
   append(45);
   append(32);
   append(77);
   append(96);
   append(21);
   append(17); // Again, 數字任意給出
  }
  void append(int N)
  {
   TNode* NewNode=(TNode *)malloc(sizeof(TNode));
   NewNode->value=N;
  
   if(root==NULL)
   {
   root=NewNode;
   return;
   }
   else
   {
   TNode* temp;
   temp=root;
   while((N>=temp.value && temp.left!=NULL) || (N<temp. value && temp. right!=NULL
  ))
   {
   while(N>=temp.value && temp.left!=NULL)
   temp=temp.left;
   while(N<temp.value && temp.right!=NULL)
   temp=temp.right;
   }
   if(N>=temp.value)
   temp.left=NewNode;
   else
   temp.right=NewNode;
   return;
   }
  }

2寫出下列程式在X86上的運行結果。

struct mybitfields
{
unsigned short a : 4;
unsigned short b : 5;
unsigned short c : 7;
}test

void main(void) 
{
int i;
test.a=2;
test.b=3;
test.c=0;

i=*((short *)&test);
printf("%d/n",i);
}

3寫出下列程式的運行結果。

unsigned int i=3;
cout<<i * -1;

4寫出下列程式所有可能的運行結果。

int a;
int b;
int c;

void F1()
{
b=a*2;
a=b;
}

void F2()
{
c=a+1;
a=c;
}

main()
{
a=5;
//Start F1,F2 in parallel
F1(); F2();
printf("a=%d/n",a);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.