English 中文(简体)
c++中有没有一种方法可以确保类成员函数不会更改任何类数据成员?
原标题:Is there a way in c++ to make sure that class member function isnt changing any of the class data members?
  • 时间:2011-06-02 10:31:43
  •  标签:
  • c++
  • syntax

比方说我有一个

class Dictionary
{
vector<string> words;  
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}

Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members. P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer.

最佳回答

如果希望编译器强制执行此操作,请声明成员函数<code>const</code>:

bool contains(string word) const
{
    ...
}

const函数不允许修改其成员变量,只能调用其他const成员函数(其自身或其成员变量)。

此规则的例外情况是,如果成员变量被声明为<code>可变的[但是mutable不应用作通用的const解决方法;它只适用于对象的“可观察”状态应为const,但内部实现(如引用计数或延迟求值)仍需要更改的情况。]

还要注意,<code>const</code>不会通过例如指针传播。

综上所述:

class Thingy
{
public:
    void apple() const;
    void banana();
};

class Blah
{
private:
    Thingy t;
    int *p;
    mutable int a;

public:
    Blah() { p = new int; *p = 5; }
    ~Blah() { delete p; }

    void bar() const {}
    void baz() {}

    void foo() const
    {
        p = new int;  // INVALID: p is const in this context
        *p = 10;      // VALID: *p isn t const

        baz();        // INVALID: baz() is not declared const
        bar();        // VALID: bar() is declared const

        t.banana();   // INVALID: Thingy::banana() is not declared const
        t.apple();    // VALID: Thingy::apple() is declared const

        a = 42;       // VALID: a is declared mutable
    }
};
问题回答

将它们标记为<code>const</code>:

bool contains(string word) const
//                        ^^^^^^

Another positive thing: You can only call other const member functions! :) Yet another good thing: You re allowed to call those functions on const objects of your class, example:

void foo(const Dictionary& dict){
  //  dict  is constant, can t be changed, can only call  const  member functions
  if(dict.contains("hi")){
    // ...
  }
  // this will make the compiler error out:
  dict.addWord("oops");
}

通常将方法声明为“const”可以实现以下目的:

bool contains(string word) const
// ...

编译器将告诉您是否在类成员上使用任何不是const的方法。还要注意,您可以通过引用传递字符串以避免复制(使<code>word</code>参数<code>std::string const&;</code〕)。

将函数声明为const:

void addWord(string word) const { /... }

If you try to change any members inside the body, the compiler will give an error. Also note that inside a method declared const, you can t call other methods that are not declared const.

使成员函数常量:

bool contains(string word) const
{
//...
}




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签