下面图老师小编跟大家分享一个简单易学的C++箴言:只要可能就用const教程,get新技能是需要行动的,喜欢的朋友赶紧收藏起来学习下吧!
【 tulaoshi.com - 编程语言 】
关于 const 的一件美妙的事情是它允许你指定一种语义上的约束:一个特定的对象不应该被修改。而编译器将执行这一约束。它允许你通知编译器和其他程序员,某个值应该保持不变。如果确实如此,你就应该明确地表示出来,因为这样一来,你就可以谋取编译器的帮助,确定这个值不会被改变。char greeting[] = "Hello";
char *p = greeting; // non-const pointer,
// non-const data
const char *p = greeting; // non-const pointer,
// const data
char * const p = greeting; // const pointer,
// non-const data
const char * const p = greeting; // const pointer,
// const data
void f1(const Widget *pw); // f1 takes a pointer to a
// constant Widget object
void f2(Widget const *pw); // so does f2
std::vectorint vec;
...
const std::vectorint::iterator iter = // iter acts like a T* const
vec.begin();
*iter = 10; // OK, changes what iter points to
++iter; // error! iter is const
std::vectorint::const_iterator cIter = //cIter acts like a const T*
vec.begin();
*cIter = 10; // error! *cIter is const
++cIter; // fine, changes cIter
class Rational { ... };
const Rational operator*(const Rational& lhs, const Rational& rhs);
Rational a, b, c;
...
(a * b) = c; // invoke operator= on the
// result of a*b!
if (a * b = c) ... // oops, meant to do a comparison!
class TextBlock {
public:
...
const char& operator[](std::size_t position) const // operator[] for
{ return text[position]; } // const objects
char& operator[](std::size_t position) // operator[] for
{ return text[position]; } // non-const objects
private:
std::string text;
};
TextBlock tb("Hello");
std::cout tb[0]; // calls non-const
// TextBlock::operator[]
const TextBlock ctb("World");
std::cout ctb[0]; // calls const TextBlock::operator[]
void print(const TextBlock& ctb) // in this function, ctb is const
{
std::cout ctb[0]; // calls const TextBlock::operator[]
...
}
std::cout tb[0]; // fine - reading a
// non-const TextBlock
tb[0] = ’x’; // fine - writing a
// non-const TextBlock
std::cout ctb[0]; // fine - reading a
// const TextBlock
ctb[0] = ’x’; // error! - writing a
// const TextBlock
tb[0] = ’x’;
class CTextBlock {
public:
...
char& operator[](std::size_t position) const // inappropriate (but bitwise
{ return pText[position]; } // const) declaration of
// operator[]
private:
char *pText;
};
来源:http://www.tulaoshi.com/n/20160219/1600501.html
看过《C++箴言:只要可能就用const》的人还看了以下文章 更多>>
如果您有什么好的建议或者疑问,可以联系我们。 商务合作QQ:3272218541;3282258740。商务合作微信:13319608704;13319603564。
加好友请备注机构名称。让我们一起学习、一起进步tulaoshi.com 版权所有 © 2019 All Rights Reserved. 湘ICP备19009391号-3
微信公众号