1、對於如下程序:
- #include <iostream>
- using namespace std;
- class A
- {
- public:
- A()
- {
- cout<<"A"<<endl;
- }
- };
- int main(void)
- {
- A a[4], b,*p;
- }
會輸出多少個A?( C )
A、2 B、3 C、5 D、6
p只是一個對象指針,並沒有指向一個對象的內存空間,所以沒有調用構造函數。
2、頭文件中的 ifndef/define/endif 有什麼作用?
答:防止該頭文件被重複引用,避免變量、類型等被重新定義。
3、const 有什麼用途?(請至少說明兩種)
答:(1)可以定義 const 常量。
(2)const可以修飾函數的參數、返回值,甚至函數的定義體。被const修飾的東西都受到強制保護,可以預防意外的變動,能提高程序的健壯性。
4、如下的字符串函數,用於生存一個字符串 ”連接號碼異常” ,並返回它的指針
- char* strfun()
- {
- char str[20];
- strcpy(str, “連接號碼異常”);
- printf(“%s \n”, str); //printf語句1
- return str;
- }
- void main()
- {
- char *pstr = strfun();
- printf("%s \n", pstr); //printf語句2
- }
問題1 : printf語句1和printf語句2哪個能在屏幕上正在打印出來?
問題2 : 如果不能正常在屏幕上打印出字符串,請說明原因。
問題3 : 如果不修改strfun的聲明,請問該如何修改上述程序的錯誤。
答:
問題1:語句1可以正常打印,語句2不能正常打印;
問題2:語句2使用的指針所指向的內存空間str[20],在函數strfun返回時已經被釋放了;
問題3:可以將函數strfun中的語句char str[20];改爲char *str = new char[20];
5、下面是交換兩個double型數據的函數,
- void swap( double* p1, double* p2 )
- {
- double *p;
- *p = *p1;
- *p1 = *p2;
- *p2 = *p;
- }
- void main()
- {
- double a = 0.1;
- double b = 0.2;
- swap( &a, &b );
- }
請找出上述代碼的錯誤,指出錯誤的原因,並改正。
答:函數swap中混淆了double型指針與double型變量的差別,對於一個未初始化的指針訪問其內存空間是非常危險的。對swap函數修改如下:
- void swap( double* p1, double* p2 )
- {
- double p;
- p = *p1;
- *p1 = *p2;
- *p2 =p;
- }
6、在電信業務的後臺處理程序中,經常會涉及到處理字符串,除了用char *處理字符串之外,C++還爲我們提供了封裝了的字符串類string,其本質也是用一個動態數組來保存字符串,類String的原型爲:
- class String
- {
- public:
- String(const char *str = NULL); // 普通構造函數
- String(const String &other); // 拷貝構造函數
- ~String(void); // 析構函數
- String & operate =(const String &other); // 賦值函數
- private:
- char *m_data; // 用於保存字符串
- };
請編寫String的上述4個函數普通構造函數、拷貝構造函數、析構函數和賦值函數。
代碼如下:
- class String
- {
- private:
- char *m_data;
- public:
- String();
- String(const char *str = NULL);
- String(const String &other);
- ~String(void);
- String & operator =(const String &other);
- };
- String::String()
- {
- m_data = NULL;
- }
- String::String(const char *str = NULL) //帶一個指針的普通構造函數
- {
- if(str == NULL)
- {
- m_data = new char[1];
- assert(m_data != NULL);
- *m_data = '\0';
- }
- else
- {
- int length=strlen(str);
- m_data = new char[length+1];
- assert(m_data != NULL);
- strcpy(m_data,str);
- }
- }
- String::String(const String &other) //拷貝構造函數
- {
- m_data = new char[other.length+1];
- assert(m_data != NULL);
- strcpy((*this).m_data,other.m_data);
- }
- String::~String(void) //析構函數
- {
- if(m_data != NULL)
- {
- delete m_data;
- m_data = NULL;
- }
- }
- String & String::operator=(const String &other) //賦值函數
- {
- if(&other != this)
- {
- delete [](*this).m_data;
- (*this).m_data = new char[other.length+1];
- assert((*this).m_data != NULL);
- strcpy((*this).m_data,other.m_data);
- }
- }