avatar

目录
c++笔记

c++ pointer

pointer arithmetic

c
1
2
3
4
5
*p++   // same as *(p++): increment pointer, and dereference unincremented address
*++p // same as *(++p): increment pointer, and dereference incremented address
++*p // same as ++(*p): dereference pointer, and increment the value it points to
(*p)++ // dereference pointer, and post-increment the value it points to
*p++ = *q++; // equivalent to *p = *q; ++p; ++q;

const pointer

c++
1
2
const int* a = &b; //the value is a const
const int* const a = &b; // the value is a const, and the pointer is also a const

pointer and string literals

c++
1
const char * foo = "hello";  // foo needs to be const otherwise it is not allowed to be assigned

void pointer cast

c++
1
2
3
4
char* pChar;
void* pVoid;
pChar = (char*)pVoid; //OK in both C and C++
pChar = pVoid; //OK in C, not OK in C++. Convertion is implicit in C

null pointer

c++
1
2
3
4
int * p = 0;
int * q = nullptr;
int * r = NULL;
cout << *r<<endl; // won't be able to compile

pointer to function

c++
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
// pointer to functions
#include <iostream>
using namespace std;

int addition (int a, int b)
{ return (a+b); }

int subtraction (int a, int b)
{ return (a-b); }

int operation (int x, int y, int (*functocall)(int,int))
{
int g;
g = (*functocall)(x,y);
return (g);
}

int main ()
{
int m,n;
int (*minus)(int,int) = subtraction;

m = operation (7, 5, addition);
n = operation (20, m, minus);
cout <<n;
return 0;
}

c++ dynamic memory

usage of new

https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory/

new returns an address of newly allocated memory to a pointer.

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int *foo;
int i = 2;
foo = new int[i]; // As we can see here, the size can be a variable(determined in run time), this is the difference between array and new
foo = new int[i]; // if allocation fails, an exception is thrown

// example with new with initialization
int *p = new int(25);
float *q = new float(75.25);
int *d = new int[5]{1,2,3,4,5};

//note: foo is NOT arrau
size_t x = sizeof(foo); // x will not be the array length, but 8 bytes (which is the length of a pointer address). This is different from array
//example:
int *foo = new int[5];
size_t x = sizeof(foo);
cout << x << endl;
// output: 8 (pointer length)

int bar[5]= {};
size_t y = sizeof(bar);
cout << y << endl;
// output: 20 (array length)

exception when using new

c++
1
2
3
4
5
6
7
	
foo = new int [5]; // if allocation fails, an exception is thrown
foo = new (nothrow) int [5]; // no exception is thrown if allocation fails
//In this case, if the allocation of this block of memory fails, the failure can be detected by checking if foo is a null pointer:
if (foo == nullptr) {
// error assigning memory. Take measures.
}

delete

c++
1
2
3
4
5
int *foo = new int;
delete foo;
int *foo = new int[10];
delete[] foo;
// if new[] is used, delete[] must be used otherwise there is memory leak.

c-malloc usage

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/

difference between new and malloc

https://www.geeksforgeeks.org/new-vs-malloc-and-free-vs-delete-in-c/

https://www.geeksforgeeks.org/malloc-vs-new/

new malloc()
calls constructor does not calls constructors
It is an operator It is a function
Returns exact data type Returns void *
on failure, Throws bad_alloc exception On failure, returns NULL
size is calculated by compiler size is calculated manually

c++ type aliases

http://www.cplusplus.com/doc/tutorial/other_data_types/

c++ enum class

c++
1
2
3
4
5
6
7
enum class Colors {black, blue, green, cyan, red, purple, yellow, white};
Colors mycolor;

mycolor = Colors::blue;
if (mycolor == Colors::green) mycolor = Colors::red;

enum class EyeColor : char {blue, green, brown};// types are not int anymore.

c++ vector

https://www.cplusplus.com/reference/vector/vector/

vector definition

c++
1
2
3
vector<int>  vector_name;
vector<int> (3,100); // it means vector<int> {100, 100, 100}
vector<vector<int> vector>;

vector methods

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vector.size();
vector.at(x);
vector.push_back();
vector.pop_back();
vector.front();
vector.back();
std::vector<int>::iterator it = myvector.begin()

// This inserts 2 of 300 after the first three elements of the vector
// new_it is a pointer to the first element of the new vector
new_it = vector.insert (it + 3,2,300);

// if the arguments are pointers, the inserted elements will be the contents between the values these pointers pointed to
int myarray [] = { 501,502,503 };
it = vector.insert (vector.begin(), myarray, myarray+3);

vector iteration

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::vector<int>::iterator it = myvector.begin()
for (it=myvector.begin(); it<myvector.end(); it++){
cout << *it << endl;//example vector loop
}

// below is an example of vector loop using iterator
std::vector<float> myvector {1,2,3};
for (std::vector<float>::iterator it=myvector.begin(); it != myvector.end(); it++){
std::cout << *it << std::endl;
}

for (auto member: vector{
cout << member << endl;
//This is another way of iterate a vector
}

c++ diff between int x, const int &a

https://blog.csdn.net/must_5/article/details/89677308

c++ lvalue and rvalue

https://zhuanlan.zhihu.com/p/111826434

c++ class

simple class example

c++
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
30
31
32
33
34
35
36
37
38
39
40
41
42
// overloading class constructors
#include <iostream>
using namespace std;

class Rectangle {
int width, height;
public:
Rectangle ();
Rectangle (int,int);
int area (void) {return (width*height);}
};

Rectangle::Rectangle () {
width = 5;
height = 5;
}

Rectangle::Rectangle (int a, int b=1) {
width = a;
height = b;
}

int main () {
Rectangle rect (3,4);
Rectangle rectb; // default constructor
Rectangle rectc {5,6}; // uniform init
Rectangle rectd = {7, 8};// pdo-like init
Rectangle recte; // default constructor called
Rectangle rectf(); // function declaration (default constructor NOT called)
Rectangle rectg{}; // default constructor called


cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area()<< endl;
cout << "rectc area: " << rectc.area()<< endl;
cout << "rectd area:" << rectd.area() << endl;
cout << "recte area: " << recte.area()<< endl;
// cout << "rectf area: " << rectf.area()<< endl;
// rectf.area() is not able to be called because the constructor is not being called
cout << "rectg area:" << rectg.area() << endl;
return 0;
}

output:

Code
1
2
3
4
5
6
rect area: 12 
rectb area: 25
rectc area: 30
rectd area:56
recte area: 25
rectg area:25

initializer list

http://www.cplusplus.com/reference/initializer_list/initializer_list/

member initialization

the following example shows member initialization method.

It is required to use member initialization method if member is a class which needs input to run constructor.

c++
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
#include <iostream>

class SampleClass {
private:
int a;
public:
SampleClass(int x) {a=x;}
int get_a_value(){return a;}
};

class IniatiazaVariable {
private:
SampleClass sample;
public:
IniatiazaVariable(): sample(0) {}
IniatiazaVariable(int x): sample(x) {}
SampleClass& get_sample() {return sample;}
};

int main()
{
IniatiazaVariable test_variable_1;
IniatiazaVariable test_variable_2 (1);
std::cout << test_variable_1.get_sample().get_a_value() << std::endl;
std::cout << test_variable_2.get_sample().get_a_value() << std::endl;
return 0;

}

output:

Code
1
2
0
1

pointer to class example

c++
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
// pointer to classes example
#include <iostream>
using namespace std;

class Rectangle {
int width, height;
public:
Rectangle(int x, int y) : width(x), height(y) {}
int area(void) { return width * height; }
};


int main() {
Rectangle obj (3, 4);
Rectangle * foo, * bar, * baz;
foo = &obj;
bar = new Rectangle (5, 6);
baz = new Rectangle[2] { {2,5}, {3,6} };
cout << "obj's area: " << obj.area() << '\n';
cout << "*foo's area: " << foo->area() << '\n';
cout << "*bar's area: " << bar->area() << '\n';
cout << "baz[0]'s area:" << baz[0].area() << '\n';
cout << "baz[1]'s area:" << baz[1].area() << '\n';
delete bar;
delete[] baz;
return 0;
}

operator overloading example

c++
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>

class SampleClass {
private:
int a;
public:
SampleClass () {}
SampleClass (int x) : a(x) {}
// member operator overloading function example declaration
SampleClass operator + (const SampleClass&);
// member operator overloading function example declaration
bool operator > (const SampleClass&);
// this is a const member inline function
const int& get_a_value () const {return a;}
};

// non-member operator overloading example declaration
bool operator < (const SampleClass& class_1, const SampleClass& class2);

// member operator overloading function example definition
SampleClass SampleClass::operator + (const SampleClass& sample_class) {
SampleClass result_class;
result_class.a = a + sample_class.a;
return result_class;
}

// member operator overloading function example definition
bool SampleClass::operator > (const SampleClass& sample_class) {
bool result;
result = a > sample_class.a ? true: false;
return result;
}

// non-member operator overloading example
bool operator < (const SampleClass& class_1, const SampleClass& class2) {
bool result;
result = (class_1.get_a_value() < class2.get_a_value()) ? true : false;
return result;
}

int main()
{
SampleClass class_1(1);
SampleClass class_2(2);
SampleClass result_class;
result_class = class_1 + class_2;
std::cout << "class_1 a value plus class_2 a value?:" << std::endl;
std::cout << result_class.get_a_value() << std::endl;
std::cout << "class_1 a value greater than class_2 a value?:" << std::endl;
std::cout << (class_1 > class_2) << std::endl;
std::cout << "class_1 a value smaller than class_2 a value?:" << std::endl;
std::cout << (class_1 < class_2) << std::endl;

return 0;
}

result:

Code
1
2
3
4
5
6
class_1 a value plus class_2 a value?:        
3
class_1 a value greater than class_2 a value?:
0
class_1 a value smaller than class_2 a value?:
1

template class

c++
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
#include <iostream>

// A typical template class
template <class T>
class SampleClass {
public:
T element;
SampleClass(T arg) {element = arg;}
};

// class template specialization
template <>
class SampleClass <char> {
public:
char element;
SampleClass (char arg) {element=arg;}

};

int main(){
SampleClass <int> sample_int(2);
SampleClass <double> sample_double(2.2);
SampleClass <char> sample_char('j');
std::cout << sample_int.element << std::endl;
std::cout << sample_double.element << std::endl;
std::cout << sample_char.element << std::endl;
return 0;
}

move/copy constructor and assignment

Code
1
2
3
4
5
6
MyClass fn();            // function returning a MyClass object
MyClass foo; // default constructor
MyClass bar = foo; // copy constructor
MyClass baz = fn(); // move constructor
foo = bar; // copy assignment
baz = MyClass(); // move assignment

example

c++
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
using namespace std;

class SampleClass {
private:
string *ptr;
public:
//constructor
SampleClass() {ptr = new string("default");}
//constructor
SampleClass(const string& str) {ptr = new string(str);}
//copy constructor declaration
SampleClass(const SampleClass& copy_class);
//move constructor declaration
SampleClass(SampleClass&& copy_class);
//destructor
~SampleClass() {delete ptr;}
//copy assignment declaration
SampleClass& operator= (const SampleClass& copy_class);
//move assignment declaration
SampleClass& operator= (SampleClass&& copy_class);
// Function to return *ptr value declaration, defined as const member function
const string& get_ptr_value() const;
};

//move constructor definition
SampleClass::SampleClass(SampleClass&& copy_class) {
ptr = copy_class.ptr;
copy_class.ptr = nullptr;
}

//copy constructor definition
SampleClass::SampleClass(const SampleClass& copy_class) {
ptr = new string(copy_class.get_ptr_value());
}

//move assignment definition
SampleClass& SampleClass::operator= (SampleClass&& copy_class){
delete ptr;
ptr = copy_class.ptr;
copy_class.ptr = nullptr;
return *this;
}


// Function to return *ptr value definition
const string& SampleClass::get_ptr_value() const {
return *ptr;
}

//copy assignment definition
SampleClass& SampleClass::operator= (const SampleClass& copy_class) {
delete ptr;
ptr = new string(copy_class.get_ptr_value());
return *this;
}

// A function to return a rvalue SampleClass instance
SampleClass get_temp_sample(SampleClass sample){
return sample;
}

int main() {
SampleClass a;
SampleClass b("okok");
cout << "a string value is: " << a.get_ptr_value() << endl;
cout << "b string value is: " << b.get_ptr_value() << endl;
SampleClass c;
cout << "c string value is: " << c.get_ptr_value() << endl;
c = b;
cout << "c string value after c = b is: " << c.get_ptr_value() << endl;
SampleClass d(b);
cout << "d string value is: " << d.get_ptr_value() << endl;
SampleClass e = get_temp_sample(SampleClass("369"));
cout << "e string value is: " << e.get_ptr_value() << endl;
e = get_temp_sample(SampleClass("okok"));
cout << "e string value after move assignment is: " << e.get_ptr_value() << endl;
return 0;
}

评论