这是我以前准备找工做时看《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