const int val = 5;
const char* const p = "hello";
const std::string str{ "world" };
当const出现在星号左边,表示被指物是常量;如果出现在星号右边,表示指针自身是常量;如果出现在星号两边,表示被指物和指针两者都是常量
const char * p;(此处可以不初始化) p指向的内容是常量
char *const p; p本身是常量
const char * const p; p和p指向的内容都是常量
int num1 = 8;
const int & num2 = num1; //常引用,不能通过引用去修改被引用的指(引用必须初始化)
int & const num3 = num1; //error
const int & const num4 = num1; //error
如果不需要改动参数或local对象,尽量加上const:
void func(const std::string & str);
令函数返回一个常量指,往往可以降低因客户错误而造成的意外,而不至于放弃安全性和高效性
const int func(void);
class A{
public:
/* A(int a, std::string str){
m_a = a;
m_name = str;
} */
A(int a, std::string str):m_a(a),m_name(str)
{
}
public:
const int m_a;
const std::string & m_name;
};
const修饰成员函数,本质修饰的是this指针;
class TextBlock{
public:
const char& operator[](std::size_t position)const
{
return text[position];
}
char& operator[](std::size_t position)
{
return
const_cast<char&>( //将op[]的返回值移除const
static_cast<const TextBlock&>(*this)[position] //为*this加上const,调用[]
);
}
private:
std::string text;
};
常对象只能调用常成员函数;普通对象既可以调用常成员函数也可以调用普通成员函数
class A{
public:
/* A(int a, std::string str){
m_a = a;
m_name = str;
} */
A(int a, std::string str):m_a(a),m_name(str)
{
}
void get()const
{
std::cout << "call const A& A::get()const" << std::endl;
std::cout << this->m_a << ' ' << this->m_name << ' ' << std::endl;
}
void get()
{
std::cout << "call A& A::get()" << std::endl;
std::cout << this->m_a << ' ' << this->m_name << ' ' << std::endl;
// return static_cast<const A&>(*this).get();
}
public:
const int m_a;
const std::string & m_name;
};
void test()
{
A a(8,"hello");
a.get();
const A ca(9, "world");
ca.get();
}
?
原文:https://www.cnblogs.com/s3320/p/11804647.html