【发布时间】: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