关闭

c++ const

572人阅读 评论(0) 收藏 举报

1.const的使用:
使用的两种形式:
const declaration ;
变量定义使用const必须进行初始化
member-function const ;
当const修饰类成员函数时限制该成员函数修改调用它的类对象。
一些例子:

const char *p        = "Hello";          // non-const pointer,
                                         // const data
char const *p        = "Hello";          // non-const pointer,
                                         // const data
char * const p       = "Hello";          // const pointer,
                                         // non-const data
const char * const p = "Hello";          // const pointer,
                                         // const data

上面的第一条语句和第二条语句是等效的,都是指针指向的DATA为常量,是两种不同习惯的表示法。

2.使用const在类中声明常量:
class GamePlayer {
private:
  static const int NUM_TURNS = 5;    // static const int类型可以在类内定义和初始化,在类外可以不再定义
  static const float f;              // 在类中只能声明,不能定义和初始化,还必须在类外定义才可以使用
  int scores[NUM_TURNS];             // use of constant
  ...
};
为什么用static?
To limit the scope of a constant to a class, you must make it a member, and to ensure there's at most one copy of the constant, you must make it a static member。

You must still define static class members in an implementation file:(except static const int)
const float GamePlayer::f;      // mandatory definition;static变量在类外定义
                                      // goes in class impl. file

3.使用const修饰函数返回值:主要是为了安全,禁止对函数返回值进行一些不合理的操作
const Rational operator*(const Rational& lhs,
                         const Rational& rhs);

Why should the result of operator* be a const object?
Having a function return a constant value often makes it possible to reduce the incidence of client errors without giving up safety or efficiency. In fact, as Item 29 demonstrates, using const with a return value can make it possible to improve the safety and efficiency of a function that would otherwise be problematic.

4.const成员函数
类的const成员函数只能被该类的const对象调用,而类的非const成员函数则只能被它的非const对象调用。类可以根据const属性来重载成员函数。
class String {
public:
  ...
  // operator[] for non-const objects
  char& operator[](int position)
  { return data[position]; }

  // operator[] for const objects
  const char& operator[](int position) const
  { return data[position]; }
private:
  char *data;
};
String s1 = "Hello";
cout << s1[0];                  // calls non-const
                                // String::operator[]
const String s2 = "World";
cout << s2[0];                  // calls const
                                // String::operator[]

String s = "Hello";                      // non-const String object
cout << s[0];                            // fine — reading a
                                         // non-const String
s[0] = 'x';                              // fine — writing a
                                         // non-const String
const String cs = "World";               // const String object
cout << cs[0];                           // fine — reading a
                                         // const String
cs[0] = 'x';                             // error! — writing a
                                         // const String
调用const operator[]的,因为const operator[]返回一个const,所以不能修改,而调用非const operator[]的,因为非const operator[]函数返回的不是const,所以可以修改。

Also note that the return type of the non-const operator[] must be a reference to a char — a char itself will not do. If operator[] did return a simple char, statements like this wouldn't compile:
s[0] = 'x';
That's because it's never legal to modify the return value of a function that returns a built-in type. Even if it were legal, the fact that C++ returns objects by value (see Item 22) would mean that a copy of s.data[0] would be modified, not s.data[0] itself, and that's not the behavior you want, anyway.

注意:如果要使修改非const operator[]的返回值,即s[0] = 'x';有效,则非const operator[]必须返回一个引用,而不能返回一个值。

class String {
public:
  // the constructor makes data point to a copy
  // of what value points to
  String(const char *value): lengthIsValid(false) { ... }
  ...
  size_t length() const;
private:
  char *data;
  size_t dataLength;                // last calculated length
                                    // of string
  bool lengthIsValid;               // whether length is
                                    // currently valid
};
size_t String::length() const
{
  if (!lengthIsValid) {
    dataLength = strlen(data);      // error!
    lengthIsValid = true;           // error!
  }
  return dataLength;
}

一个类的const成员函数定义时不能修改该类的成员数据。

5.修饰参数的const,
如 void fun0(const A* a ); void fun1(const A& a);
调用函数的时候,用相应的变量初始化const常量,则在函数体中,按照const所修饰的部分进行常量化,如形参为const A* a,则不能对传递进来的指针的内容进行改变,保护了原指针所指向的内容;如形参为const A& a,则不能对传递进来的引用对象进行改变,保护了原对象的属性。

在参数中使用const应该使用引用或指针,而不是一般的对象实例。 这很好理解,你有没有看到过

void fun(const int a);

这样的函数,应该没有吧,一般只有

void fun(const int& a);

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:107750次
    • 积分:1605
    • 等级:
    • 排名:千里之外
    • 原创:47篇
    • 转载:18篇
    • 译文:0篇
    • 评论:16条
    最新评论