c++ syntax

This article records my C++ learning notes, keeps developing…

Chinese Version: 这篇文章记录我对C++学习心得和基本使用方法,以便以后手生的时候快速上手。

Template

C++用template来实现Java中generic class的功能

注意问题:

test.h里面声明类Circletest.cpp中的每一个member function前面都要申明。

template<class K, class V> class Circle{};

Array

C++中Array的长度没有像Java一样封装,一定要自己设置一个变量去约束。常用做法:

int array[20] = malloc(20*sizeof(int)) --提前分配出空间,不然容易出现指针为NULL的异常

Pointer

Basic Intuition:

1
2
3
4
5
6
7
int n = 3

-- p_n stores the address of n; * is declaring pointer; & is reference operator
int* p_n = &n;

-- m stores value 3; * is dereference operator
int m = *p_n;

Pointer & Array

1
2
3
4
int* p_array = int array[20];	
int* p_array = new int[20];

Circle** p_array = new Circle*[20];

注意!Circle* p_array = new Circle[20] 创建的是一个包含Circle整个实例的数列,需要有Circle里面有default constructor.

String Comparision

1
2
char nts1[] = "Test";
char nts2[] = "Test”;

The value of ptr_hash(nts1)==ptr_hash(nts2) is false. Cause, you are hashing two different string pointers pointing to same string.

Read File by Word

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
using namespace std;

int () {
ifstream myfile;
myfile.open ("ants-sample-data/antsin");
string line;
if (myfile.is_open()){
for(int i = 0; myfile >> line; i++)
cout << line << 'n';
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

Calculate Funtion Runtime

1
2
3
4
5
6
7
#include <time.h>
clock_t t = clock();

function_to_measured();

t = clock() - t;
total_runtime += ((float)t)/CLOCKS_PER_SEC;

Class

1
2
3
4
5
6
7
class Circle{
private:
int height = 2;
-- Wrong! Only static const integral data members can be initialised within a class.
public:

}