在类的函数中使用'const'

ggg*_*ggg 26 c++ oop const class

我已经看到很多使用const关键字放在类中的函数之后,所以我想知道它是什么.我在这里读了一下:http://duramecho.com/ComputerInformation/WhyHowCppConst.html.

它表示使用const是因为函数"可以尝试改变对象中的任何成员变量".如果这是真的,那么它应该在任何地方使用,因为我不希望以任何方式改变或改变任何成员变量.

class Class2
{ void Method1() const;
  int MemberVariable1;} 
Run Code Online (Sandbox Code Playgroud)

那么,const的真正定义和用途是什么?

R S*_*hko 37

可以在const对象上调用const方法:

class CL2
{
public:
    void const_method() const;
    void method();

private:
    int x;
};


const CL2 co;
CL2 o;

co.const_method();  // legal
co.method();        // illegal, can't call regular method on const object
o.const_method();   // legal, can call const method on a regulard object
o.method();         // legal
Run Code Online (Sandbox Code Playgroud)

此外,它还告诉编译器const方法不应该更改对象的状态并将捕获这些问题:

void CL2::const_method() const
{
    x = 3;   // illegal, can't modify a member in a const object
}
Run Code Online (Sandbox Code Playgroud)

通过使用mutable修饰符,上述规则有一个例外,但在进入该领域之前,首先应该先了解const正确性.


Joh*_*ing 5

其他人回答了关于const成员函数的问题的技术方面,但这里有一个更大的图片 - 这就是const正确性的想法.

简而言之,const正确性是关于澄清和强制执行代码的语义.举一个简单的例子.看看这个函数声明:

bool DoTheThing(char* message);
Run Code Online (Sandbox Code Playgroud)

假设有人写了这个函数,你需要调用它.你知道DoTheThing()你的char缓冲区有什么用吗?也许它只是将消息记录到文件中,或者它可能会更改字符串.通过查看函数声明,您无法分辨调用的语义.如果函数不修改字符串,则声明const不正确.

使您的函数const正确也具有实用价值.也就是说,根据调用的上下文,如果没有一些技巧,您可能无法调用const不正确的函数.例如,假设您知道DoTheThing()不会修改传递给它的字符串的内容,并且您拥有以下代码:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(msg.c_str());
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将无法编译,因为msg.c_str()返回a const char*.为了使这段代码能够编译,你必须做这样的事情:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(msg.begin());
}
Run Code Online (Sandbox Code Playgroud)

......甚至更糟:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(const_cast<char*>(msg.c_str()));
}
Run Code Online (Sandbox Code Playgroud)

可以说,这两者都不比原始代码"更好".但是因为DoTheThing()以不正确的方式编写,你必须围绕它弯曲你的代码.