C++点滴----关于类常成员函数

关于C++中,类的常成员函数

声明样式为:   返回类型 <类标识符::>函数名称(参数表) const

一些说明:

1、const是函数声明的一部分,在函数的实现部分也需要加上const

2、const关键字可以重载函数名相同但是未加const关键字的函数

3、常成员函数不能用来更新类的成员变量,也不能调用类中未用const修饰的成员函数,只能调用常成员函数。即常成员函数不能更改类中的成员状态,这与const语义相符。

例一:说明const可以重载函数,并且实现部分也需要加const

#include <iostream>
using namespace std;

class TestA
{
public:
  TestA(){}
  void hello() const;
  void hello();
};
void TestA::hello() const
{
  cout << "hello,const!" << endl;
}
void TestA::hello()
{
  cout << "hello!" << endl;
}

int main()
{
  TestA testA;
  testA.hello();
  const TestA c_testA;
  c_testA.hello();
}

运行结果:

例二:用例子说明常成员函数不能更改类的变量,也不能调用非常成员函数,但是可以调用常成员函数。非常成员函数可以调用常成员函数

#include <iostream>
using namespace std;

class TestA
{
public:
  TestA(){}
  TestA(int a, int b)
  {
    this->a = a;
    this->b = b;
  }
  int sum() const;
  int sum();
  void helloworld() const;
  void hello();
private:
  int a,b;
};
int TestA::sum() const
{
  //this->a = this->a + 10;//修改了类变量,编译时会报错误1 
  //this->b = this->b + 10;//同上 
  //  hello();  //调用了非成员函数,编译时报错误2
  return a + b;
}
int TestA::sum()
{
  this->a = this->a + 10;
  this->b = this->b + 10;
helloworld();
//可以调用常成员函数 return a + b; } void TestA::helloworld() const { cout << "hello,const" << endl; } void TestA::hello() { cout << "hello" << endl; } int main() { TestA testA; testA.sum(); const TestA c_testA; c_testA.sum(); }

当注释去掉时,编译会报错误1,表示类的常成员函数不能修改类的变量。

错误2如下,表示常成员函数不能调用非常成员函数

 

posted @ 2016-06-30 23:33  魄魄熊  阅读(8550)  评论(0编辑  收藏  举报