forked from shangerxin/BookNotes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathC++ 14 Quick Syntax Reference(Second Edition)=Mikael Olsson;Note=Erxin.txt
1555 lines (1180 loc) · 39.9 KB
/
C++ 14 Quick Syntax Reference(Second Edition)=Mikael Olsson;Note=Erxin.txt
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
C++ 14 Quick Syntax Reference(Second Edition)=Mikael Olsson;Note=Erxin
# Hello World
- choosing a IDE
+ VS
+ NetBeans
+ Eclipse CDT
- hello world
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world";
cin.get();
}
# Compile and run
- console compilation, GNU compiler collection(GCC), install it by minGW or cygWin
$ g++ MyApp.cpp -o MyApp.exe
- comments
//single-line comment
/* multi-line comment*/
# variables
- data types
data type size(byte) description
char 1
short 2
int 4
long 4 or 8
long long 8
float 4
double 8
long double 8 or 16
the int type will have the same size as the process's word size. 32bit system will be 32
- declaring variables
type variable-name;
- assigning variables
variable-name = value;
type variable-name = value;
int variable-name(value); //constructor initialization
int x = 1, y = 2, z;
- variable scope, have globally and locally scope
+ global, define outside of any code blocks. it is accessible from anywhere after defined
int global;
global variable automatic init to zero
+ local, declare in function, will not automatic initialize
int main(){
int local;
}
- integer types
char myChar = 0; // -128 to +127
short myShort = 0; // -32768 to +32767
int myInt = 0; // -2^31 to +2^31-1
long myLong = 0; // -2^31 to +2^31-1
+ c++ 11 added
long long myL2 = 0; // -2^63 to +2^63-1
+ determine the exact size of a data type by. it will return the bytes number
sizeof(variable-name);
+ fixed-sized integer types added in C++ 11. these types belong to the std namespace
#include <cstdint>
using namespace std;
int8_t myInt8 = 0; // 8 bits
int16_t myInt16 = 0; // 16 bits
int32_t myInt32 = 0; // 32 bits
int64_t myInt64 = 0; // 64 bits
- signed and unsigned integers, by default MS VC is signed integer
signed char myChar = 0; // -128 to +127
signed short myShort = 0; // -32768 to +32767
signed int myInt = 0; // -2^31 to +2^31-1
signed long myLong = 0; // -2^31 to +2^31-1
signed long long myL2= 0; // -2^63 to +2^63-1
unsigned char myChar = 0; // 0 to 255
unsigned short myShort = 0; // 0 to 65535
unsigned int myInt = 0; // 0 to 2^32-1
unsigned long myLong = 0; // 0 to 2^32-1
unsigned long long myL2= 0; // 0 to 2^64-1
short and long data types are abbreviations of short int and long int
short myShort; // short int
long myLong; // long int
- numeric literals, integers can be assigned b using octal or hexadecimal notation
int myOct = 062; //octal notation
int myHex = 0x32; //hexadecimal notation
+ c++ 14 there is a binary notation which uses '0b' as its prefix
int mybin = 0b010'1010'1010; // binary notation "'" is a digit separator for easier to read long numbers
- floating point types
float t; //~7 digits
double dt; //~15 digits
long double ldt; //typically same as double
+ can be assigned by using either decimal exponential notation or exponential notation
t = 3e2; //3*10^2 300
- literal suffixes. integer can be combination of U and L for unsigned and long respectively
int i = 10 ;
long i = 10L;
unsigned long ul = 10UL;
+ floating type suffix, without suffix a floating literal is double
float f = 1.23F;
double d = 1.23;
long double ld = 1.23L;
- char type. commonly used to represent ascii characters
char c = 'x';
- bool type
bool b = false;
# operators
- operator types can be grouped into five
arithmetic
assignment
logical
biwise
- arithmetic
int x = 3 + 2; // 5 // addition
x = 3 - 2; // 1 // subtraction
x = 3 * 2; // 6 // multiplication
x = 3 / 2; // 1 // division
x = 3 % 2; // 1 // modulus (division remainder)
explicit convert value
float f = 3 / (float)2; // 1.5
- assignment operators
=
- compbined assignment operators
x += 5; // x = x+5;
x -= 5; // x = x-5;
x *= 5; // x = x*5;
x /= 5; // x = x/5;
x %= 5; // x = x%5;
- increment and decrement operators
x++; // x = x+1;
x--; // x = x-1;
- comparison operators
bool b = (2 == 3); // false // equal to
b = (2 != 3); // true // not equal to
b = (2 > 3); // false // greater than
b = (2 < 3); // true // less than
b = (2 >= 3); // false // greater than or equal to
b = (2 <= 3); // true // less than or equal to
- logical operator, if the result already determined then the right-hand side of the and and or operator will not be evaluated
bool b = (true && false); // false // logical and
b = (true || false); // true // logical or
b = !(true); // false // logical not
- bitwise operators
int x = 5 & 4; // 101 & 100 = 100 (4) // and
x = 5 | 4; // 101 | 100 = 101 (5) // or
x = 5 ^ 4; // 101 ^ 100 = 001 (1) // xor
x = 4 << 1; // 100 << 1 =1000 (8) // left shift
x = 4 >> 1; // 100 >> 1 = 10 (2) // right shift
x = ~4; // ~00000100 = 11111011 (-5) // invert
+ bitwisze operators have combined assignment operators
int x=5; x &= 4; // 101 & 100 = 100 (4) // and
x=5; x |= 4; // 101 | 100 = 101 (5) // or
x=5; x ^= 4; // 101 ^ 100 = 001 (1) // xor
x=5; x <<= 1;// 101 << 1 =1010 (10)// left shift
x=5; x >>= 1;// 101 >> 1 = 10 (2) // right shift
- operator precedence
pre operator pre operator
1 :: 9 == !=
2 () [] . -> x++ x-- 10 &
3 ! ~ ++x --x x* x& (type) 11 ^
4 .* ->* 12 |
5 * / % 13 &&
6 + - 14 ||
7 << >> 15 ?: = op=
8 < <= > >= 16 ,
- logical and && binds weaker than relational operators
bool b = 2+3 > 1*4 && 5/5 == 1; // true
better way
bool b = ((2+3) > (1*4)) && ((5/5) == 1); // true
# pointers
- pointer is a variable that contains the memory address of another variable, called pointee
- create pointers
int* p; // pointer to an integer
int *q; // alternative syntax
+ retrieve address or a variable. use address-of operator(&)
int* p; // pointer to an integer
int *q; // alternative syntax
- dereferencing pointers, dereference operator(*)
*p;
int* p2 = p; //copy of p (copies address stored in p)
- pointing to a pointer
int** r = &p; //pointer to p
- dynamic allocation
int* d = new int //dynamic allocation
delete d; //release
- null pionter
trying to delete an already deleted null pointer is safe however if deleting twice to a non null pointer will cause memory corruption
p != 0;
p != NULL
p != nullptr;
nullptr could only be implicitly converted to pointer or bool types
# References
- create a new name for a variable.
int x;
int& r = x; //r is an alias to x
once the reference has been assigned it can never be reset
- references and pointers, pointer is a variable that points to another variable and reference is only an alias and does not have an address of its own
int* ptr = &x; //ptr assigned address to x
generally whenever a pointer does not need to be reassigned a reference should be used instead. reference is safe because it always need to refer before use
reference the nullptr will cause invalid memory access
int* ptr = 0;
int& ref = *ptr;
ref = 10; //segmentation fault(invalid memory access)
- rvalue reference, bind and modify temporary objects (rvalues)
int&& ref = 1+2; //rvalue reference
rvalue reference extends the lifetime of the temporary object
# Arrays
- a data structure for stroing a collection of values that all have the same data type
- array declaration and allocation
int ary[2];
+ assignment
ary[0] = 1;
+ init
int ary[] = {1,2,3};
int ary[3] = {1,2,3};
- multi-dimention arrays
int ary[2][2] = {{0,1}, {2,3}};
int ary[2][2] = {0, 1, 2, 3};
- dynamic arrays
int* p = new int[3]; //dynamic allocated
*(p+1) = 10; //p[1] = 10;
- array size
sizeof(regular_array);
this method is not suitable for dynamic allocate arrays
int* p = new int[size];
delete[] p;
# String
- in the standard namespace
#include <string>
using namespace std;
string h = "hello";
string w("world");
- string combining
string a = h+w;
h += w;
it is not possible to concatenate two c string or two string literals, to do this need to explictt convert to string
string literals will also be implicitly combine if the plus sign is left out
char* p = "Hel" "lo";
- escape characters
\n, \t, \v vertical tab, \b backspace, \r, \0 null character, \f form feed, \a alert sound, \' signle quote, \" double quote, backslash
any one of 128 ascii can be expressed by writing a backslash followed by the ascii code
"\07f" //octal character
"\0x177"
+ c++ 11 escape characters can be ignored by adding a "R" before the string
string escaped = R"(c:\windows\system32\cmd.exe)";
- string compare
s0 == s1;
- string functions
- string encodings
wchar_t is provied. string literals of this type are created by prepending the string with a capital "L", the result can be stored using wstring class
wstring s1 = L"hello";
wchar_t* s2 = L"hello";
+ fixed-sized character type were introduced in c++ 11 namely char16_t and char32_t. these types provide definite of the utf-16 and utf-32. utf-32 are prefixed with "U"
string s = u8"utf-8 string";
u16string s4 = u"utf-16 string";
u32string s5 = U"utf-32 string";
string s6 = u8"An asterisk: \u002A";
# Conditionals
- if statement
if(experssion)
{
}
else if(expression)
{
}
else
{
}
- switch
switch(x)
{
case 0: ; break;
...
default: ; break;
}
- ternary operator
expression = expression ? value: value;
the programming term expression refers to code that evaluates to a value, a statement is a code segment that ends with a semicolon or a closing curly bracket.
# Loops
- while loop
while(expression){
}
- do while
do
{
}while(expression);
- for loop
for(statement; expression; statement){
}
for(;;)
{
//infinit loop
}
+ c++ 11 introduce a range-based for loop syntax
int a[3]={1,2,3};
for(int &i: a)
{
count << i; //"123"
}
- break and continue
for(int i = 0; i < 10; i ++)
{
break;
continue;
}
- goto statement, a third jump statement whic performs an unconditional jump to a specified label
goto label;
lable:
...
# functions
- definiting functions
return_type funciton_name(parameter_list)
{
[return xx;]
}
- calling function
func_name();
- default parameter
void foo(string a, string b = "hello")
{
}
foo("a");
- function overloading, a function could be define multiple times in c++
void foo(string a, string b);
void foo(string a);
void foo(int a);
- return statement, a function can return a value
void foo(){return 0;}
- forward declaration
void foo(int a);
void foo(int a)
{
}
- pass by value, both primitive and object data types are by default passed by value
- pass by reference
+ pass by address
+ pass by reference
+ return by value, reference or address
return by reference is commonly used to return an argument that has also been passed to the function by reference
int& byref(int& i){return i;}
return by address also need to make sure the return value is log in the local function scope
- inline fuction, for small function that are called inside loops
inline int myinc(int i) {return i++;}
- auto and decltype, c++ 11 introduced these are used for type deduction during compilation
auto i = 5;
auto transflates to the core type of the initializer which means that any reference that constant specifiers are dropped
int& iref = i;
auto myauto = iref; //int
drooped specifiers can be manually reapplied as needed
auto& myref = iref; //int&
alternatively two ampersands can be used
int i = 1;
auto&& a = i; //int& lvalue reference
auto&& b = 2; //int&& rvalue reference
+ auto specifier can be used anywhere
vector<int> v {1,2,3};
for(auto& i: v){...}
- decltype specifier works similar to auto, except it deduces the exact declared type of a given expression, including references. this expression is specified in parentheses
decltype(3) b = 3 //int&&
+ in c++14 auto may be used as the expression for decltype
decltype(auto) = 3; //int&&
- auto is often the simpler choice when an initializer is vailable, decltype is mainly used to forward function return types without consider whether it is a reference or value type
decltype(5) getFive() {return 5;} //int
- c++ 11 added a trailing return type syntax, it allows a function's return value to be specified after the parameter list following the arrow operator (->) this enables the parameter to be used when deducing the return type with decltype
auto getValue(int x) -> decltype(x) // int
{
return x;
}
+ c++ 14 enabled the core return type to be deduced directly from the return statement
auto getValue(int x){return x;}
decltype(auto) getRef(int &x) {return x;} //int&
in modern ide you can hover over a variable to check its type even if the type has been automatically deduced
- lambda functions c++ 11
auto sum = [](int x, int y) -> int
{
return x + y;
};
+ c++ 14 the tail trailing is not needed
auto sum = [](int x, int y){return x + y;};
+ lambda are typically used for specifying simple functions that are only referenced once
#include <iostream>
#include <functional>
using namespace std;
void call(int arg, function<void(int)> func) {
func(arg);
}
int main() {
auto printSquare = [](int x) { cout << x*x; };
call(2, printSquare); // "4"
}
+ captured by value is default, use &variable_name to capture by reference
//by value
void call(function<void()> func) { func(); }
int main() {
int i = 2;
auto printSquare = [i]() { cout << i*i; };
call(printSquare); // "4"
}
//by reference
int a = 1;
[&a](int x) { a += x; }(2);
cout << a; // "3"
shorthand for capture A [=] means the variables are captured by value and [&] captures them by reference.
+ c++ 14 support initialized inside the capture clause
int a = 1;
[&, b = 2]() { a += b; }();
cout << a; // "3"
# Class
- class is a template used to create objects
class className
{
int field_name;
int method(){};
};
inline int MyRectangle::getArea() { return x * y; }
int className::method()
{
}
members can be declared inside the class, two main kidns are fields and methods;
- inline methods if the function is short and want to recommend the compiler to inserted into the caller's code, one way to do this would to use the inline keyword in the method definition
define a method inside a class will implicitly recommend to be inline
- object creation
className instance;
- forward declaration
class MyClass;
MyClass* p; // allowed
MyClass f(MyClass&); // allowed
MyClass o; // error, definition required
sizeof(MyClass); // error, definition required
# Constructor
- a class can contain a constructor, for instantiate the object
- overloading
class MyRectangle
{
public:
int x, y;
MyRectangle();
MyRectangle(int, int);
};
MyRectangle::MyRectangle() { x = 10; y = 5; }
- this keyword
- field initialization from the constructor give better performance than initiate inside the constructor
MyRectangle::MyRectangle(int a, int b) : x(a), y(b) {}
- default constructor
- destructor, a class can also have an explicitly defined destructor. it is used to release any resources allocated by the object
class Semaphore
{
public:
bool *sem;
Semaphore() { sem = new bool; }
~Semaphore() { delete sem; }
};
- special member functions
+ constructor
+ destructor
+ copy constructor
+ copy assignment operator (operator =)
+ c++11 came way of controlling whether to allow these special member or not through the delete and default specifiers. delete forbids the calling of a function, default compiler generated default will be used
class A
{
public:
// Explicitly include default constructor
A() = default;
A(int i);
// Disable copy constructor
A(const A&) = delete;
// Disable copy assignment operator
A& operator=(const A&) = delete;
};
- object initialization, c++ 11 provide several ways
+ direct initialization
ClassName c(5)
+ value initialization A value initialization creates only a temporary object, which is destroyed at the end of the statement. To preserve the object it must either be copied to another object or assigned to a reference.
const ClassName& a = MyClass();
MyClass&& b = MyClass();
value initialized object is almost identical to one created by using default initialization. A minor difference is that non-static fields will in some cases be initialized to their default values when using value initialization.
+ copy initialization This works because of the implicit copy constructor that the compiler provides, which is called for these kinds of assignments
MyClass a = MyClass();
- new initialization
+ initialized through dynamic memory allocation by using the new keyword
// New initialization
MyClass* a = new MyClass(); MyClass& b = *new MyClass();
// ...
delete a, b;
- aggregate initialization, enable fields to be set by using a brace enclosed list of initializer, it only could be used when class does not have constructor and virtual functions or base classes. the fields must be public or static
MyClassa = { 2 }; // iis 2
- uniform initialization, c++ 11 to provide a consistent way to initialize types
// Uniform initialization
MyClass a { 3 }; // i is 3
int i { 1 };
string s {"Hello"};
int a[] { 1, 2 };
int *p= new int [2] { 1, 2 };
vector<string> box { "one", "two" };
+ uniform initialization can be used to call constructor
// Call parameterless constructor
MyClass b {};
// Call copy constructor
MyClass c { b };
+ A class can define an initializer-list-constructor. This constructor is called during uniform initialization and takes priority over other forms of construction. The argument list can be any length but all elements must be of the
same type.
#include <iostream>
using namespace std;
class NewClass
{
public:
NewClass(initializer_list<int> args)
{
for (auto x : args)
cout << x << " ";
}
};
int main()
{
NewClass a { 1, 2, 3 }; // "1 2 3"
}
# inheritance
- inheritance allows a class to acquire the members of another class except its constructors and destructor
class Rectangle
{
public:
int x, y;
int getArea() { return x * y; }
};
class Square : public Rectangle {};
- upcasting, an object can be upcast to its base class because it contains everything that the base class contains. a derived class can be used anywhere a base class is expected
- downcasting, has to be made explicit and downcast a base class to a inherite class is not allowed
- constructor inheritance
+ base class constructor is automatically called default constructor
+ explicit call base class constructor by
class B2
{
public:
int x;
B2(int a) : x(a) {}
};
class D2 : public B2
{
public:
D2(int i) : B2(i) {} // call base constructor
};
+ c++ 11 support inherit constructor, base class constructor can't initialize derived class. derived class should initialize themselves, this is done here using the uniform notation
class D2 : public B2
{
public:
using B2::B2; // inherit all constructors
int y{0};
};
- multiple inheritance
class Person {}
class Employee {}
class Teacher: public Person, public Employee {}
# Overriding
- redefine a method in a base class from derived class
- hiding derived members,
class Rectangle
{
public:
int x, y;
int getArea() { return x * y; }
};
class Triangle : public Rectangle
{
public:
Triangle(int a, int b) { x = a; y = b; }
int getArea() { return x * y / 2; }
};
Triangle t = Triangle(2,3);
t.getArea(); // 3 (2*3/2) calls Triangle's version
Rectangle& r = t;
r.getArea(); // 6 (2*3) calls Rectangle's version
- overriding derived members, redefine a method upward in the class hierarchy what is called overriding
class Rectangle
{
public:
int x, y;
virtual int getArea() { return x * y; }
};
Calling the getArea method from Rectangle’s interface will now invoke Triangle’s implementation.
Rectangle& r = t;
r.getArea(); // 3 (2*3/2) calls Triangle's version
+ C++11 added the override specifier
virtual float getArea() override {} // error - no base class method to override
+ Another specifier introduced in C++11 is final. This specifier prevents a virtual method from being overridden in derived classes
class Base
{
virtual void foo() final {}
}
class Derived
{
void foo() {} // error: Base::foo marked as final
}
- base class scoping, It is still possible to access a redefined method from a derived class by typing the class name followed by the scope resolution operator.
class Triangle : public Rectangle
{
public:
Triangle(int a, int b) { x = a; y = b; }
int getArea() { return Rectangle::getArea() / 2; }
};
# Access levels
- three available in c++
public
protected
private
- private are accessible in the class they are declared
- protected also be accessed from inside a derived class
- public gives unrestricted access
- access level guideline
- friend classes and functions
+ a class can be allowed to access the private and protected members of another class by declaring the class as a friend
class MyClass
{
int myPrivate;
// Give OtherClass access
friend class OtherClass;
};
class OtherClass
{
void test(MyClass c) { c.myPrivate = 0; } // allowed
};
+ a global function can be also declared as a friend
class MyClass
{
int myPrivate;
// Give myFriend access
friend void myFriend(MyClass c);
};
void myFriend(MyClass c) { c.myPrivate = 0; } // allowed
- public, protected and private inheritance
# Static
- static keyword is used to create class members that exist in only one copy, which belongs to the class itself
- static fields, cannot be initialized inside the class. it must be defined outside of the class declaration. this initialization will only take place once
class MyCircle
{
public:
double r; // instance field (one per object)
static double pi; // static field (only one copy)
};
double MyCircle::pi = 3.14;
int main()
{
double p = MyCircle::pi;
}
- static methods, they are independent of any instance variables
class MyCircle
{
public:
double r; // instance variable (one per object)
static double pi; // static variable (only one copy)
double getArea() { return pi * r * r; }
static double newArea(double a) { return pi * a * a; }
};
int main()
{
double a = MyCircle::newArea(1);
}
- static local variables, A static local variable is only initialized once when execution first reaches the declaration, and that declaration is then ignored every subsequent time the execution passes through.
- static global variables, This will limit the accessibility of the variable to only the current source file, and can therefore be used to help avoid naming conflicts.
# Enum
- is a user-defined type consisting of a fixed list of named constants, Enum constants may be prefixed with the enum name for added clarity. However,
these constants are always unscoped
enum Color { Red, Green, Blue };
Color c = Color::Red;
- enum constant values, By default, the first constant in the enum list has the value zero and each successive constant is one value higher.
+ explicit specify values
enum Color
{
Red = 5, // 5
Green = Red, // 5
Blue = Green + 2 // 7
};
- enum conversions, implicit convert an enumeration constant to an integer, convert integer to enum required explicit
- enum scope, enum could also be declare inside a class or localling within a function
class MyClass
{
enum Color { Red, Green, Blue };
};
void myFunction()
{
enum Color { Red, Green, Blue };
}
- strongly typed enums, c++ 11 provide a safer alternative to the regular enum with additional class keyword
enum class Speed
{
Fast,
Normal,
Slow
};
Speed s = Speed::Fast;
the new enum the specified constants belong within the scope of the enum class name. must qualified with the enum name to access
Speed s = Speed::Fast;
+ the underlying regular enum value is not define in standard it may vary between implementation. in contrast a class enum always uses the int type by default and can be overridden by other integer type. enum class will not be implicit convert to integer
enum class MyEnum : unsigned short {};
# struct and union
- struct are used instead of classes to represent simple data structures that mainly contain public fields
struct Point
{
int x, y; //public
};
class Point
{
int x, y; //private
};
- declarator list
Point p, q;
struct Point
{
int x, y;
} r, s;
+ c++ 11 uniform initialization syntax
Point p = { 2, 3 };
- union, all fields share the same memory position, union size of the largest field it contains
union Mix
{
char c[4]; // 4 bytes
struct { short hi, lo; } s; // 4 bytes
int i; // 4 bytes
} m;
this allowed access 4 bytes in multiple ways
- anonymous union cannot contain methods or non-public members.
int main()
{
union { short s; }; // defines an unnamed union object s = 15;
}
global anonymous union must be static
static union {};
# operator overloading
- binary operator overloading to simplify the input Since the class now overloads the addition sign, this operator can be used to perform the calculation needed.
MyNum c = a + b;
Keep in mind that the operator is only an alternative syntax for calling the actual method.
MyNum d = a.operator + (b);
- unary operator overloading, With unary operators, a reference of the same type as the object should always be returned. This is because when using a unary operator on an object, programmers expect the result to return the same object and not just a copy
MyNum& operator++() // ++ prefix
{ ++val; return *this; }
Not all unary operators should return by reference. The two postfix operators – post-increment and post-decrement – should instead return by value. Note that the postfix operators have an unused int parameter specified. This parameter is used to distinguish them from the prefix operators.
MyNum operator++(int) // postfix ++
{
MyNum t = MyNum(val);
++val;
return t;
}
- overloadable operators
+ binary operators + - * / %, = += -= *= /= %= &= ^= |= <<= >>= == != > < >= <= & | ^ << >> && || -> ->*
+ unary operators + - ! ~ & * ++ -- special operators () [] delete new
+ not overloadable . .* :: ?: # ## sizeof
# custom conversions
- convert allow an object to be constructed from or converted to another type
class myNum
{
public:
int value;
};
- implicit conversion, constructor need to added that takes a single parameter of the desired type
class MyNum
{
public:
int value;
MyNum(int i) { value = i; }
};
this will work for the implicit convert chain. such as char can implicit convet to int then it will be implicit convert to MyNum too
MyNum d = 'h';
- explicit conversion constructor
class MyNum
{
public:
int value;
explicit MyNum(int i) { value = i; }
};
MyNum A = 5; // error
MyNum B(5); // allowed
MyNum C = MyNum(5); // allowed
- conversion operators, custom conversion operators allow conversion to be specified in the other direction from object type to another. operator keyword with target type
class MyNum
{
public:
int value;
operator int() { return value; }
};
MyNum A { 5 };
int i = A; // 5
- explicit conversion operators c++ 11
class True
{
explicit operator bool() const {
return true;
}
};
True a, b;