hello~ 很高兴见到大家! 这次带来的是C++中关于C++11这部分的一些知识点,如果对你有所帮助的话,可否留下你宝贵的三连呢? 个 人 主 页: 默|笙

接上次的博客<C++11(一)>
template<class... Args> void Func(Args... args) {}
template<class... Args> void Func(Args&... args) {}
template<class... Args> void Func(Args&&... args) {}template <class ...Args>
void Print(Args&&... args)//...是放在&&的后面的
{
cout << sizeof...(args) << endl;
}
int main()
{
//结合引用折叠实例化为void Print()
Print();
//实例化为void Print(int&& arg1)
Print(1);//args函数包有一个形参
int x;
//实例化为void Print(int&& arg1, int& arg2)
Print(1, x);//两个
//实例化为void Print(int&& arg1, string&& arg2, int& arg3)
Print(1, string("111"), x);//三个
return 0;
}void ShowList()
{
cout << endl;
}
template <class T, class ...Args>
void ShowList(T x, Args... args)
{
cout << x << " ";
ShowList(args...);
}
template <class ...Args>
void Print(Args... args)
{
ShowList(args...);
}
int main()
{
int x = 1;
Print(1, string("111"), x);
return 0;
}




class Person
{
public:
Person(const char* name = "张三", int age = 10)
:_name(name)
, _age(age)
{}
/*~Person()
{}*/
private:
mosheng::string _name;
int _age = 1;
};
int main()
{
Person s1;
Person s2 = s1;
Person s3 = std::move(s1);
Person s4;
s4 = std::move(s2);
return 0;
}有自主实现的析构函数之前,move(s1)会调用移动构造,而s4会调用移动赋值重载:

实现之后,编译器没有生成默认移动构造和移动赋值重载:

class Person
{
public:
Person(const char* name = "张三", int age = 10)
:_name(name)
, _age(age)
{}
~Person()
{}
Person(const Person& p) = default;
Person(Person&& p) = default;
Person& operator=(const Person& p) = default;
Person& operator=(Person && p) = default;
private:
mosheng::string _name;
int _age = 1;
};
int main()
{
Person s1;
Person s2 = s1;
Person s3 = std::move(s1);
Person s4;
s4 = std::move(s2);
return 0;
}
class Example {
public:
Example(int a, int b)
:_x(a)
,_y(b)
{
cout << "目标构造函数\n";
}
//Example(int a)
// : Example(a, 0)
// ,_y(1) // 编译报错,因为_y已经在被委托的构造函数里面初始化了
//{
// cout << "委托构造函数\n";
//}
Example(int a)
: Example(a, 0)
{
cout << "委托构造函数\n";
}
int _x;
int _y;
};class Base {
public:
Base(int x, double d)
:_x(x)
, _d(d)
{
}
Base(int x)
:_x(x)
{
}
Base(double d)
:_x(d)
{
}
protected:
int _x = 0;
double _d = 0;
};
//传统的派生类实现构造
class Derived : public Base {
public:
Derived(int x) : Base(x) {}
Derived(double d) : Base(d) {}
Derived(int x, double d) : Base(x, d) {}
};
//C++11继承基类的所有构造函数
//1、没有成员变量的派生类
//2、成员变量都有缺省值,并且我们就想用这个缺省值初始化
class Derived : public Base {
public:
using Base::Base;
protected:
int _i;
string _s;
};今天的分享就到此结束啦,如果对读者朋友们有所帮助的话,可否留下宝贵的三连呢~~ 让我们共同努力, 一起走下去!