1:C++构造函数的default和delete
C++11中,当类中含有不能默认初始化的成员变量时,可以禁止默认构造函数的生成,
myClass()=delete;//表示删除默认构造函数
myClass()=default;//表示默认存在构造函数
当类中含有不能默认拷贝成员变量时,可以禁止默认构造函数的生成,
myClass(const myClass&)=delete;//表示删除默认拷贝构造函数,即不能进行默认拷贝
myClass & operator=(const myClass&)=delete;//表示删除默认拷贝构造函数,即不能进行默认拷贝
原文链接
2:取消定义宏
# define PI 3.14159 定义宏
# undef PI 取消定义宏
3:assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行。
4:typedef void (*HandleFile)(const char *direction, const char *name)。
作用:定义HandleFile为一个指向函数的指针,且被指向的函数的返回值为void,参数为(const char *direction, const char *name)
5:char * fgets(char * s, int n,FILE *stream);
参数:
s: 字符型指针,指向存储读入数据的缓冲区的地址。
n: 从流中读入n-1个字符
stream : 指向读取的流。
返回值:
1. 当n<=0 时返回NULL,即空指针。
2. 当n=1 时,返回空串"".
3. 如果读入成功,则返回缓冲区的地址。
4. 如果读入错误或遇到文件结尾(EOF),则返回NULL.
6:std::move()
在C++11中,标准库在<utility>中提供了一个有用的函数std::move,std::move并不能移动任何东西,它唯一的功能是将一个左值强制转化为右值引用,继而可以通过右值引用使用该值,以用于移动语义。
#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
{
std::string str = "Hello,World!";
std::vector<std::string> v;
//调用常规的拷贝构造函数,新建字符数组,拷贝数据
v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
//调用移动构造函数,掏空str,掏空后,最好不要使用str
v.push_back(std::move(str));
std::cout << "After move, str is \"" << str << "\"\n";
std::cout << "The contents of the vector are \"" << v[0]
<< "\", \"" << v[1] << "\"\n";
}
After copy, str is “Hello,World!”
After move, str is “”
The contents of the vector are “Hello,World!”, “Hello,World!”
7:c语言32个关键字
c_keywords = {
"auto", "double", "int", "struct", "break", "else",
"long", "switch", "case", "enum", "register", "typedef",
"char", "extern", "return", "union", "const", "float",
"short", "unsigned", "continue", "for", "signed", "void",
"default", "goto", "sizeof", "volatile", "do", "if",
"while", "static"};
8:extern关键字
我们知道,程序的编译单位是源程序文件,一个源文件可以包含一个或若干个函数。在函数内定义的变量是局部变量,而在函数之外定义的变量则称为外部变量,外部变量也就是我们所讲的全局变量。它的存储方式为静态存储,其生存周期为整个程序的生存周期。全局变量可以为本文件中的其他函数所共用,它的有效范围为从定义变量的位置开始到本源文件结束。
然而,如果全局变量不在文件的开头定义,有效的作用范围将只限于其定义处到文件结束。如果在定义点之前的函数想引用该全局变量,则应该在引用之前用关键字 extern 对该变量作外部变量声明,表示该变量是一个已经定义的外部变量。有了此声明,就可以从“声明”处起,合法地使用该外部变量。
#include <stdio.h>
int max(int x,int y);
int main(void)
{
int result;
/*外部变量声明*/
extern int g_X;
extern int g_Y;
result = max(g_X,g_Y);
printf("the max value is %d\n",result);
return 0;
}
/*定义两个全局变量*/
int g_X = 10;
int g_Y = 20;
int max(int x, int y)
{
return (x>y ? x : y);
}
代码中,全局变量 g_X 与 g_Y 是在 main 函数之后声明的,因此它的作用范围不在 main 函数中。如果我们需要在 main 函数中调用它们,就必须使用 extern 来对变量 g_X 与 g_Y 作“外部变量声明”,以扩展全局变量的作用域。也就是说,如果在变量定义之前要使用该变量,则应在使用之前加 extern 声明变量,使作用域扩展到从声明开始到本文件结束。
原文地址
9:const类型
const int *p
解释:不能给*p赋值,但是可以给p赋值
10:函数内声明函数
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
void Fun(int a, int b) {
auto fun = [&](int s) {
int sum = 0;
for (int i = 0; i <= s; ++i) {
sum += i;
}
return sum;
};
cout << fun(a) + fun(b) << endl;
}
int main()
{
int a = 10;
int b = 10;
Fun(a, b);
return 0;
}