栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【C++】学习笔记:21天学通C++ 第1-14章重点选摘

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【C++】学习笔记:21天学通C++ 第1-14章重点选摘

学习笔记:21天学通C++ 第1-14章重点选摘

Type* Pointer = new Type;
delete Pointer;

Type* Pointer = new Type[numElements];
delete[] Pointer;

不想处理bad_alloc,可使用new(nothrow),在内存分配失败时返回NULL。

不许被复制的类

class President
{
private:
	President(const President&);
	President& opreator= (const President&);
}

单例类

Class President
{
private:
	President(){};
	President(const President&);
	const President& operator=(const President&);

	string name;
  
public:
	static President& GetInstance()
	{
	static President onlyInstance;
	return onlyInstance;
	}
}

使用 explict 避免隐式转换

共用体

union UnionName
{
	Type1 member1;
	Type2 member2;
 
 	...
	TypeN memberN;
};  	

virtual, override 保证虚函数被覆盖, final 禁止覆盖虚函数,禁止继承

单目前缀递增运算符

Date& operator++()
{
	// operator implementation code
	return *this;
}

后缀递增运算符

Data operator++(int)
{
	Data copy(*this);
	// increment implementation code
	return copy; 
}

转换运算符

operator const char*()
{
	ostringstream formattedDate;
	cout << “Holiday is on: ” << holiday << endl;
	dateInString = formattedData.str();
	return dataInString.c_str();
}

智能指针std::unique_prt

移动构造函数和移动赋值函数

class Sample
{
private:
	Type* ptrResource;
public:
	Sample(Sample&& moveSource)
	{
	ptrResource = moveSource.ptrResource;
	moveSource.ptrResource = NULL;
 	}
	Sample operator=(Sample&& moveSource)
	{
 	if(this !=&moveSource)
	{
     delete[] ptrSource;
     ptrResource = moveSource.ptrResource;
   	moveSource.ptrResource = NULL;
	}
}

Sample();
Sample(const Sample& copySource);
Sample& operator= (const Sample& copySource);
}

用户定义的字面量

ReturnType operator “” YourLiteral(ValueType value) {// conversion code here}

C++类型转换运算符

static_cast
dynamic_cast // runtime type identification
reinterpret_cast
const_cast

语法:destination_type result = cast_operator(object_to_cast);

使用#define定义常量#define identifier value

使用宏避免多次被包含

#ifndef HEADER_H_
#define HEADER_H_
...
#endif

使用assert验证表达式 assert(expression that evaluates to true or false);

模板函数:调用模板函数无需指定模板参数类型,而使用模板类需要这样。

template 
bool TemplateFunction(const T1& params1, const T2& params2);

对于模板类的静态成员,通用的初始化语法为
template StaticType ClassName::StaticVarName;

参数可变模板(C++14)

template 
void Sum(Res& result, First val1, Rest... valN)
{
	result = result + val1;
	return Sum(result, valN ...);
}

使用static_assert执行编译阶段检查
static_assert(expression being validated, “Error message when check fails”);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1011328.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号