马上要学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 <class T>
.- 调用时
function<Generic Type>
其中<Generic Type>会自动推断。
template <class T>
T sum( T a, T b) {
return a + b;
}
template <class T, class U>
bool are_equal(T a, U b) {
return a == b;
}
// call sum function
cout << sum<int>(10, 20) << endl;
cout << sum(10.0, 20.0) << endl; // double类型自动推断。
cout << are_equal(12, 120.0) << endl;
Scopes
Java其实也是这样的,
{}
构成了一个scope,所以在for
循环中new的变量在循环结束后就被销毁了。
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.
Arrays
declaration:
type name [elements];
initialization:int foo [5] = { 16, 2, 77, 40, 12071 };
or :int foo[] = { 10, 20, 30 };
orint foo[] { 10, 20, 30 };
Multidimensional Arrays
int jimmy [3][5];
Arrays as parameters
- passing an array as argument always loses a dimension
arrays cannot be directly copied, and thus what is really passed is a pointer.
Pointer
&
Address-of operatorfoo = &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