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如下,表示常成員函數不能調用非常成員函數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM