首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

一个简单的有关问题

2012-02-17 
一个简单的问题#include iostreamusing namespace stdclass c{private:int ipublic:int get(){return

一个简单的问题
#include <iostream>
using namespace std;
class c
{
  private:
  int i;
  public:
  int get()
  {
  return i;
  }
};
void f(const c &cc)
{
  cc.get();//这一行编译通不过
}

int main()
{
  return 0;
}

[解决办法]
LS正解...可以温习下const在c++中的用法
[解决办法]
int get()const//加上这个.
{
return i;
}
[解决办法]

探讨
1楼的朋友, 去掉const我也知道可以通过, 但是我想知道的是为什么会这样?

Complex Add(const Complex &amp;a, const Complex &amp;b);如果这行代码中的const也去掉的话, 那么效率会变得低下.

[解决办法]
int get() const{}
[解决办法]
const对象只能调用const函数的。因此有两种方法修改,第一种是吧f函数中的const去掉,第二就是把get写成const函数。
习惯上,get函数不会修改类成员,可以写成const函数

热点排行