此文为北大coursera课程《程序设计实习》(郭炜+刘家瑛主讲)个人笔记
Week 01 从C走进C++
01 FunPtr
类型名(* 指针变量名)(参数类型1, 参数类型2, ...);
函数指针名(实参表);
void
PrintMin(int a, int b)
{
if (a < b) {
printf("%d\n", a);
} else {
printf("%d\n", b);
}
}
int main()
{
void(*pf)(int, int);
int x = 4, y = 5;
pf = PrintMin;
pf(x, y);
system("pause");
return 0;
}
qsort函数:
void qsort(void *base, int nelem, unsigned int width, int(*pfCompare(const void*, const void*)));
比较函数规则: *elem1 排在 *elem 2 之前,返回负整数
*elem1 与 *elem 2 顺序无所谓,返回0
*elem1 排在 *elem 2 之后,返回正整数
02 CmdPara
获得命令行参数的程序main函数必须为 int main(int argc, char * argv[]) {...}
argc:代表程序启动时,命令行参数的个数。可执行程序本身文件名也算一个命令行参数。
argv:指针数组, 每个元素都是一个char* 类型指针,指针指向一个字符串,存放着命令行参数。
03 BitOpr
右移运算符 “>>”,结果往小里取整,对有符号数为算数右移
eg:两个int型变量a, b (0<=n<=31),写表达式使和a的第n位相同
1. (a >> n) & 1
2. (a & (1 << n)) >> n
04 Refer
定义引用时,一定需要初始化为引用某个变量,且只能引用变量,不能引用常量或表达式
// C中交换int变量
void
swap(int *a, int *b)
{
int tmp;
tmp = *a; *a = *b; *b = tmp;
}
int n1, n2;
swap(& n1, & n2);
// C++引用
void
swap(int& a, int& b)
{
int tmp;
tmp = a; a = b; b = tmp;
}
swap(n1, n2);
还可以引用作为函数返回值
int n = 4;
int&
SetValue()
{
return n;
}
int main()
{
SetValue() = 40;
std::cout << n;
return 0;
}
常引用:int n = 100; cont int &r = n; 不能通过常引用去修改其引用内容
05 Const
不可通过常量指针修改其指向内容
不能把常量指针赋给非常量指针,反过来可以
函数参数为常量指针时,可避免函数内部不小心改变参数指针所指地方内容
06 Dynamic
动态内存分配:
P = new T;
P = new T[N];
用 “new” 动态分配的内存空间,一定要用 "delete" 运算符释放
delete 指针;
delete [] 指针;
07 InlineFunctions
内联函数:把整个函数的代码插入到调用语句处,而不会生成调用函数语句。
函数重载:一个或多个函数,名字相同,参数个数或参数类型不同。
08 DefaultArg
eg: void func(int x1, int x2 = 2, int x3 = 3) { }
只能最右边的连续若干个参数缺省。
class Complex {
public:
double ral, imag;
Complex(int i) // 类型转换构造函数
{
cout << "IntConstructor called" << endl;
ral = i;
imag = 0;
}
Complex(double r, double i)
{
ral = r; imag = i;
}
};
int main()
{
Complex c1(7, 8);
Complex c2 = 12; // 初始化,非赋值
c1 = 9; // 9被自动转换成一个临时Complex对象,赋给了c1
cout << c1.ral << "," << c1.imag;
system("pause");
return 0;
}
class CTyre {
private:
int radius;
int width;
public:
CTyre(int r, int w) :radius(r), width(w) {} // 初始化列表
};
class CEngine {
};
class CCar { // 封闭类
private:
int price;
CTyre tyre;
CEngine engine;
public:
CCar::CCar(int p, int tr, int w) :price(p), tyre(tr, w) {}
};
// 一个类的友元函数可以访问该类私有成员
class CCar;
class CDriver {
public:
void ModifyCar(CCar * pCar);
private:
};
class CCar {
private:
int price;
friend int MostExpensiveCar(CCar cars[], int total); // 声明友元
friend void CDriver::ModifyCar(CCar * pCar);
};
// 将一个类的成员函数(包括构造,析构)定义为另一个类的友元
class B {
public:
void function();
};
class A {
friend void B::function();
};
class A {
int i;
public:
void Hello() {
//cout << "hello" << endl; // 输出hello
cout << i << "hello" << endl; // 出错
}// -> void Hello(A *this){ cout << "hello" << endl; }
};
int main()
{
A *p = NULL;
p->Hello();
return 0;
}
class CTest {
private:
int n;
public:
CTest() { n = 1; }
int test() const { return n; }
int test() { return 2 * n; }
};
int main()
{
const CTest objTest1;
CTest objTest2;
cout << objTest1.test() << objTest2.test() << endl;
return 0;
}