请教C++ 中的const问题

来源:百度知道 编辑:UC知道 时间:2024/09/28 11:51:35
inline double bandwidth() const { return bandwidth_; }

这里面的的const是什么意思,这个函数是什么意思?
还是不太理解,上面的函数和
inline const double bandwidth() { return bandwidth_; }
有什么区别吗?

该函数不能修改类对象.
比如说:
const CPoint point;
point.setX(1);//错误,因为修改了常量对象
point.getX();//如果getX函数为const就是正确的,并且没有修改对象
为了尊重类对象的常量性,只能声明const成员函数才能修改常量对象.
除了const还有volatile也是这样.
这样解释不知楼主是否了解
class CTest
{
public:
CTest()
{
bandwidth_=1;
}
inline double bandwidth() const { return bandwidth_; }
protected:
double bandwidth_;
};
int main()
{
const CTest test;
cout<<test.bandwidth();
}
楼主可以试试把inline double bandwidth() const { return bandwidth_; }改为inline double bandwidth() { return bandwidth_; }会报错:不能将“this”指针从“const CTest”转换为“CTest &”,再继续该把const CTest test改为CTest test,又正确了!
还是那句话当为常量对象时(const CTest test)不能调用非const函数(inline double bandwidth() { return bandwidth_;).但是还要保证const函数不能修改对象的字段.

这个函数是成员函数 const就是constant,常量的意思
一般在申明一个常对象函数后,只能调用常成员函数
常成员函数不能改变类里的数据成员的值
当然有区别了
inline const double bandwidth(){return bandwidth_;}的含义是:
定义