【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”);

猜你喜欢

转载自blog.csdn.net/weixin_56917387/article/details/125766875