【问题标题】:const method on c++ languagec++ 语言中的 const 方法
【发布时间】:2017-06-06 17:23:45
【问题描述】:

我记得,在大学里,const 方法不能改变字段。 我现在正在回归 C++,并且我已经编写了简单的程序。

#include "stdafx.h"

#include <iostream>

using namespace std;

class Box
{
    int a;
    int b;
    int square;

public:
    Box(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    const void showSquare(void) const
    {
        cout << this->a * this->b << endl;
    }

    const void setDim(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Box b(2, 4);
    b.showSquare();
    b.setDim(2, 5);
    b.showSquare();
    int a;
    cin >> a;
    return 0;
}

在我的情况下 const 方法可以更改类的字段吗? 怎么可能?

比你提前。

【问题讨论】:

  • const void setDim(int a, int b) 不是 const 方法的正确签名。那将是void setDim(int a, int b) const
  • showSquare() 使用const 表示不更改“字段”。 setDim() 使用const 表示函数的返回值没有改变(这是没有意义的,但是在返回void 时是允许的),但这与函数是否改变“字段”无关。跨度>

标签: c++ class methods constants


【解决方案1】:

您问题中的setDim 不是const 方法。该方法的返回类型是const void。由于该方法返回void,所以const 确实没有区别。

如果您希望该方法的行为类似于 const 方法(不应更改对象状态的方法),请将 const 移动到签名的末尾 p>

void setDim(int a, int b) const 
    {
       // do read only operations on the object members.
    }

How many and which are the uses of “const” in C++? 会是一个很好的复习。

【讨论】:

    【解决方案2】:

    const void 是返回值,它是 const 而不是不能改变成员数据的 const this 指针:

    class A
    {
        public:
            void show()const // this pointer here is constant so this method cannot change any member data or Call any other non-const member
            {
                a = 0; // compile time-error 
    
                setValue(7); // also compile time error: `error C2662: 'setValue' : cannot convert 'this' pointer from 'const class A' to 'class A &'`
                cout << a << endl;
            }
    
            const void setValue(const int x)
            {
                a = x; // ok
            }
    
            private:
                int a;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 2020-08-18
      • 2017-08-10
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多