Effective C++: const

 ̄綄美尐妖づ 提交于 2020-02-28 20:59:43

关于const:

1, 只有在使用指针的时候我们才说const分为 顶层(top)const 和 底层(bottom)const.

2, 右值引用你还用const你有毒吧.

3, 如果是两个指针之间相互拷贝其 底层(bottom)const 起到很关键的作用.

#include <iostream>

int main()
{
	int n = 10; //no const;
	const int n1 = 10; //just const;
	const int& n2 = 10; //just const;
	
	const int* ptr1 = nullptr; //bottom-const;
	int* const ptr2 = nullptr; //top-const;
	const int* const ptr3 = nullptr; //bottom and top-const;

	//case 0:
	const int& number1 = 10; //number的类型为: const int&;
	const int number2 = 10; //number2的类型为: const int;

	//case 1:
	int n1_ = n1; //ok;
	int n2_ = n2; //ok;
	//int* ptr1_ = ptr; //error! 不能从 const int* 转为 int*;
	int* ptr2_ = ptr2; //ok;
	//int* ptr3_ = ptr3; //error! 不能constant const int* 转为 int*;

	//case 2:
	const int* _ptr = &n1; //ok
	std::cout << *_ptr << std::endl;
	_ptr = &n;
	std::cout << *_ptr << std::endl;
	_ptr = ptr1;
	std::cout << *_ptr << std::endl;

	//*_ptr = 10; //error

       //case 3:
       //true
       std::cout << std::boolalpha << std::is_same<const char(&)[7], decltype("shihua")>::value << std::endl; 



}

 

 

4, 当在class内的时候不能在 const成员函数 里面调用 非const成员函数, 反之可以.

#include <iostream>
#include <memory>
#include <vector>
#include <string>

template<typename T>
class Node {
public:
	Node() = default;
	Node(const T& value) :data{ value } {};

	const T& getData()
	{
		return data;
	}

	const T& get()const
	{
		return data;
	}

	void printData()const //注意这里的const
	{
		std::cout << (this->getData())<< std::endl;
	}

	void print()
	{
		std::cout << (this->get()) << std::endl;
	}

private:
	T data;
};

int main()
{
	Node<int> node{ 10 };

	//case 1: 不可以在const成员函数中调用非const成员函数.
	//node.printData(); //error! 

	//case 2: 可以在非成员函数中调用调用const成员函数.
	node.print();

	return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!