C++笔记
这里是一些日常使用的C++总结,它没有什么特定的依据,碰到什么就记录什么
1、在构造函数中使用new时应该注意的事项
new和delete必须相互兼容,new对应于delete,new[]对应于delete[];
如果有构造函数中使用new来初始化成员,则应在析构函数中使用delete
2、Assert
assert原型定义在assert.h中,其作用是如果它的条件返回错误,则终点程序执行
1 assert(false); //终止程序运行 2 assert(true); //正常执行
3、const
使用const关键字来指定变量或对象在被声明之后不允许被修改
一个常量成员函数不能修改任何非静态数据,也不能调用非常量成员函数
1 class Date 2 { 3 public: 4 Date(int mn,int dy,int yr); 5 int getMonth() const; //a read-only function; 6 void setMonth(int mn);//a write function;cant't be const 7 8 private: 9 int month; 10 } 11 12 13 int Date::getMonth() const 14 { 15 return month; 16 } 17 18 void Date::setMonth(int mn) 19 { 20 month= mn; 21 } 22 23 int main() 24 { 25 Date myDate(7,4,1998); 26 const Date birthDate(1,18,1952); 27 myDate.setMonth(4) ; //ok 28 birthDate.getMonth(); //ok 29 birthDate.setMonth(4); //C2622 30 }
4、enum class
5、stringstream类简单使用
1 stringstream ss; 2 char* data = new char[260]; 3 memset(data,0,sizeof(data)); 4 5 ss<<hex; 6 ss<<12<<"abc"<<endl; 7 ss>>data; 8 9 ss<<"First"<<" "<"string,"; 10 cout<<ss.str()<<endl; 11 12 ss.str("HelloWorld"); 13 cout<<ss.str()<<endl; 14 15 //使用str函数,可以将stringstream类型转换为string类型 16 //调用ss.str("")清空 17 18 int first,second; 19 stringstream sstream; 20 sstream <<"123"; 21 sstream>>first; 22 cout<<first<<endl; 23 24 //在进行多次类型转换前,需要 调用 clear 25 sstream.clear(); 26 27 sstream<<true; 28 sstream>>second; 29 cout<<second<<endl;
6、char和unsigned char
unsigned char无符号 0-255
char 有符号 (-127-128)
7、wcout无法输出中文
setlocale(LC_ALL,NULL);
或
wcout.imbue(std::locale("chs"));
8、C++中的函数指针
1 #include<functional> 2 3 void Test(int a,int b,int c); 4 std::function<void(int a,int b,int c)> f1 = [](int a,int b,int c){};//lambda表达式 5 6 //或 7 8 std::function<void(int a,int b ,int c) = Test; 9 10 //使用函数指针 11 void(*f1)(int a,int b,int c); 12 f1 = Test; 13 14 typedef void(*func)(int a,int b,int c); 15 func f2 = Test;
9、索引器函数
C++
1 T& operator[](int index);
C#
1 T this[int index] 2 { 3 get{} 4 set{} 5 }
10、纯虚函数
1 virtual void showwindow(int show) = 0;
纯虚函数没有实现,只能子类实现
虚函数可以有实现,也可以被继承
11、传引用
传引用只在声明时指出,在调用时不需要 任何修饰符
1 void Swap(int &a,int &b); 2 3 int a = 1; 4 int b = 2; 5 Swap(a,b);
12、分配字符串
_tcsdup
需要引用tchar.h ,使用完成后,需要调用free进行释放。它的内部使用了malloc来进行内存分配
13、字符串数值转换
1 int num = _wtoi(L"1234"); 2 3 TCHAR buf[10]{}; 4 5 _itow(1234,buf,10);