這是我以前準備找工做時看《C/C++求職寶典》一書作的筆記,都是一些筆試面試中常考的重點難點問題,但比較基礎,適合初學者看。html
1. char c = '\72'; 中的\72表明一個字符,72是八進制數,表明ASCII碼字符「:」。面試
2. 10*a++ 中a先進行乘法運算再自增(筆試中常常喜歡出這類運算符優先級容易混淆的輸出問題)。算法
#include <stdio.h>
int main() {
int a[] = {10, 6, 9, 5, 2, 8, 4, 7, 1, 3};
int i, tmp;
int len = sizeof(a) / sizeof(a[0]);
for(i = 0; i < len;) {
tmp = a[a[i] - 1];
a[a[i] - 1] = a[i];
a[i] = tmp;
if(a[i] == i + 1) i++;
}
for(i = 0; i < len; ++i)
printf("%d ", a[i]);
printf("\n");
return 0;
}
double modf(double num, double *i); // 將num分解爲整數部分*i和小數部分(返回值決定)
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *p = &(a + 1)[3];
printf("%d\n", *p);
輸出:5編程
char str1[] = "abc";
char str2[] = "abc";
const char str3[] = "abc";
const char str4[] = "abc";
const char *str5 = "abc";
const char *str6 = "abc";
char *str7 = "abc";
char *str8 = "abc";
cout << (str1 == str2) << endl;
cout << (str3 == str4) << endl;
cout << (str5 == str6) << endl;
cout << (str7 == str8) << endl;
輸出:0 0 1 1數組
char *str = "abc";
printf("%p\n", str1);
cout << &str1 << endl;
上面打印的是字符串 「abc」的地址,下面打印的是 str1 變量的地址。函數
class CBook {
public:
const double m_price;
CBook() :m_price(8.8) { }
};
下面的作法是錯誤的:this
class CBook {
public:
const double m_price;
CBook() {
m_price = 8.8;
}
};
而下面的作法雖未報錯,但有個warning,也不推薦:spa
class CBook {
public:
const double m_price = 8.8; // 注意這裏若沒有const則編譯出錯
CBook() { }
};
class CBook {
public:
mutable double m_price; // 若是不加就會出錯
CBook(double price) :m_price(price) { }
double getPrice() const; // 定義const方法
};
double CBook::getPrice() const {
m_price = 9.8;
return m_price;
}
class CBook {
public:
CBook() {
cout << "constructor is called.\n";
}
~CBook() {
cout << "destructor is called.\n";
}
};
void invoke(CBook book) { // 對象做爲函數參數,若是這裏加了個&就不是了,由於加了&後是引用方式傳遞,形參和實參指向同一塊地
// 址,就不須要建立臨時對象,也就不須要調用拷貝構造函數了
cout << "invoke is called.\n";
}
int main() {
CBook c;
invoke(c);
}
解答:注意拷貝構造函數在對象做爲函數參數傳遞時被調用,注意是對象實例而不是對象引用。所以該題輸出以下:指針
constructor is called.
invoke is called.
destructor is called. // 在invoke函數調用結束時還要釋放拷貝構造函數建立的臨時對象,所以這裏還調用了個析構函數
destructor is called.
class CBook {
public:
double m_price;
CBook() {
CBook(8.8);
}
CBook(double price) : m_price(price) { }
};
int main() {
CBook c;
cout << c.m_price << endl; // 此時並不會輸出理想中的8.8
}
class CBook {
public:
static double m_price;
};
double CBook::m_price = 8.8; // 只能在這初始化,不能在CBook的構造函數或直接初始化
class A {
public:
virtual void funa();
virtual void funb();
void func();
static void fund();
static int si;
private:
int i;
char c;
};
問:sizeof(A) = ?code