c++类 花括号构造函数的使用、const引用、左值引用和右值引用(不考虑模板)(C++类相关)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值