C++ tutorial

vector

vector是一个能够存放任意类型的动态数组,能够增加和压缩数据。

inherit

derived class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

// 基类
class Shape {
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// 派生类
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};

template

举例:定义类模板

1
2
3
4
5
6
7
8
9
10
11
12
13
template<class T>
class Test {
private:
T n;
const T i;
static T cnt;
public:
Test():i(0){}
Test(T k);
~Test(){}
void print();
T operator+(T x);
};

举例:定义函数模板

1
2
3
4
template<typename(或class) T>
T fuc(T x, T y) {
T x;
}
1
2
3
4
5
int main() {
double d;
int a;
fuc(d,a);
}

系统将用实參d的数据类型double去取代函数模板中的T生成函数

1
2
3
double fuc(double x,int y) {
double x;
}

namespace

namespace通常用来给类或者函数做个区间定义,以使编译器能准确定位到适合的类或者函数。

1
2
3
4
namespace namespace_name {
// code declarations
// 函数,类名等等
}

举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

// first name space
namespace first_space{
void func(){
cout << "Inside first_space" << endl;
}
}

// second name space
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}

int main () {
// Calls function from first name space.
first_space::func();
// Calls function from second name space.
second_space::func();
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

// first name space
namespace first_space{
void func(){
cout << "Inside first_space" << endl;
}
}

// second name space
namespace second_space{
//此处func与第一处命名空间内函数名相同
void func(){
cout << "Inside second_space" << endl;
}
}

// 使用第一个namespace
using namespace first_space;
int main () {
// This calls function from first name space.
func();
return 0;
}