C++11可以用花括号构造函数增加像vector之类的容器初始化便捷性,花括号只能向宽的方向进行转换
static void newVersionConstruct() {
int avector[] = { 1, 2, 3};
std::vector<int> bv = { 1, 2, 3};
A a(10);
A b{3};
A c(true);
A d{true};
A e(1.1);
//A f{1.0};
}
新版本类成员初始化的简化:
class B {
public:
B() : m_age(18), m_height(170), m_weight(75) {}
explicit B(int age) : m_age(age), m_height(170), m_weight(75) {}
B(int age, int height)
: m_age(age), m_height(height) /*, m_height(75) forget bad */ {}
int age() const { return m_age;}
int height() const { return m_height;}
int weight() const { return m_weight;}
private:
int m_age;
int m_height;
int m_weight;
};
static void defaultInitValue() {
B a(10, 20);
NewB b(10, 20);
std::cout << "Old b age is " << a.age() << " height " << a.height()
<< " weight " << a.weight() << std::endl;
std::cout << "New b age is " << b.age() << " height " << b.height()
<< " weight " << b.weight() << std::endl;
}
在新版本中可以用{}初始化默认值为0:
class NewB {
public:
NewB() {}
explicit NewB(int age) : m_age{age} {}
NewB(int age, int height) : m_age(age), m_height{height} {}
int age() const { return m_age; }
int height() const { return m_height; }
int weight() const { return m_weight; }
private:
int m_age = 18;
int m_height = 170;
int m_weight = 75;
int m_value{};
double m_fightValue{};
};
const引用:常量引用表示不能通过引用改变绑定对象的值,但是对象的值可以通过别的方式改变。
int a = 10;
//常量引用b和a绑定,不能通过b而改变a。
const int &b = a;
cout << a << endl;
cout << b << endl;
//但是可以通过别的方式改变a
右值引用可以改变大小
左值引用转化成右值引用需要明确说明用move
static void leftRefAndRightRef() {
// 什么是引用
int a = 10;
int& refA = a;
const int& constRefA = a;
std::cout << " a " << a << " ref of a " << refA << " const ref a "
<< constRefA << std::endl;
// this is a error
//int& refB = 10;
const int& constRefB = 10;
printInfo(constRefB);
printInfo(10);
printInfo(a);
printInfo(refA);
std::cout << "different version const ref " << constRefB << std::endl;
auto&& rrA = 10;
int&& rrB = 20;
const int&& crrB = 20;
rrA = 30;
std::cout << " right ref of b " << rrB << " const right ref b "
<< crrB << std::endl;
int b = 20;
// error why?
//int&& rrB = b;
//const int&& crrB = b;
int&& newRRB = std::move(b);
const int&& cNewRRB = std::move(b);
std::cout << " b " << b << " right ref of b " << newRRB<< " const right ref b "
<< cNewRRB << std::endl;
std::cout << "address " << &b << " ref " << &newRRB << " c ref " << &cNewRRB << std::endl;
}