【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<destination_type>(object_to_cast);

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

使用宏避免多次被包含

#ifndef HEADER_H_
#define HEADER_H_
...
#endif

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

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

template <typename T1, typename T2 = T1>
bool TemplateFunction(const T1& params1, const T2& params2);

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

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

template <typename Res, typename First, typename... Rest>
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”);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值