CPlusPlus basics

马上要学compiler construction和Database implementation两门课,用的是C/C++
这是上课前预习/复习C/C++的笔记:

Overloads and templates:

Overload functions:
In C++, two different functions can have the same name if their parameters are different; either because they have a different number of parameters, or because any of their parameters are of a different type.

function templates
Defining a function template follows the same syntax as a regular function, except that it is preceded by the template keyword and a series of template parameters enclosed in angle-brackets <>:

  • 函数声明前面要加template .
  • 调用时function其中会自动推断。
template 
T sum( T a, T b) {
    return a + b;
}

template 
bool are_equal(T a, U b) {
     return a == b;
}
// call sum function
cout << sum(10, 20) << endl;
cout << sum(10.0, 20.0) << endl; // double类型自动推断。
cout << are_equal(12, 120.0) << endl;
Scopes

Java其实也是这样的,{}构成了一个scope,所以在for循环中new的变量在循环结束后就被销毁了。

CPlusPlus basics_第1张图片
image.png

Namespace

Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.


CPlusPlus basics_第2张图片
image.png
Arrays

declaration: type name [elements];
initialization: int foo [5] = { 16, 2, 77, 40, 12071 };
or : int foo[] = { 10, 20, 30 };
or int foo[] { 10, 20, 30 };

CPlusPlus basics_第3张图片
image.png

Multidimensional Arrays

int jimmy [3][5];

Arrays as parameters
  1. passing an array as argument always loses a dimension
  2. arrays cannot be directly copied, and thus what is really passed is a pointer.


    CPlusPlus basics_第4张图片
    image.png
Pointer

& Address-of operator foo = &myvar;
* "Value pointed to by" operator, i.e. baz = *foo;

问题:
https://www.w3cschool.cn/cpp/cpp-overloading.html
Box operator+(const Box& b)是什么意思?类的类型?

解析: 这涉及Cpp函数参数传递方式。
两种传递方式:Arguments passed by value and by reference

void duplicate(int a, int b) {
 // pass by value;
  a *= 2;
  b *= 2;
}

int x = 1, y = 2;
duplicate(x, y);
// x is still  1, y still 2
void duplicate(int& a, int& b) {
 // pass by reference;
  a *= 2;
  b *= 2;
}
int x = 1, y = 2;
duplicate(x, y);
// x is 2, y still 4 

值得注意的是,无论哪种参数传递方式,在函数调用者看来都是把variable穿进去。至于是传值还是传reference则看函数的实现。
所以: Box operator+(const Box& b)的意思是传b本身的reference过去。调用时仍然是box1+box2

你可能感兴趣的:(CPlusPlus basics)