函数后面 加上const

C++ const成员函数详解
类的成员函数后面加 const,表明这个函数不会对这个类对象的数据成员(准确地说是非静态数据成员)作任何改变。 

在设计类的时候,一个原则就是对于不改变数据成员的成员函数都要在后面加 const,而对于改变数据成员的成员函数不能加 const。所以 const 关键字对成员函数的行为作了更加明确的限定:有 const 修饰的成员函数(指 const 放在函数参数表的后面,而不是在函数前面或者参数表内),只能读取数据成员,不能改变数据成员;没有 const 修饰的成员函数,对数据成员则是可读可写的。 

除此之外,在类的成员函数后面加 const 还有什么好处呢?楼主告诉我们的:“获得能力:可以操作常量对象”,其实应该是常量(即 const)对象可以调用 const 成员函数,而不能调用非const修饰的函数。正如非const类型的数据可以给const类型的变量赋值一样,反之则不成立。 

对于const成员函数,"不能修改类的数据成员,不能在函数中调用其他不是const的函数",这是由const的属性决定的,楼主说得完全正确。 

请看下面一个完整的例子,然后我再作一些说明。 
#include <iostream>; 

#include <string>; 

using namespace std; 

 

class Student { 

public: 

  Student() {} 

  Student( const string& nm, int sc = 0 ) 

    : name( nm ), score( sc ) {} 

 

  void set_student( const string& nm, int sc = 0 ) 

  { 

    name = nm; 

    score = sc; 

  } 

 

  const string& get_name() const 

  { 

    return name; 

  } 

 

  int get_score() const 

  { 

    return score; 

  } 

 

private: 

  string name; 

  int score; 

}; 



// output student's name and score 

void output_student( const Student& student ) 

{ 

  cout << student.get_name() << "\t"; 

  cout << student.get_score() << endl; 

} 

 

int main() 

{ 

  Student stu( "Wang", 85 ); 

  output_student( stu ); 

}



设计了一个类 Student,数据成员有 name 和 score,有两个构造函数,有一个设置成员数据函数 set_student(),各有一个取得 name 和 score 的函数 get_name() 和 get_score()。请注意 get_name() 和 get_score() 后面都加了 const,而 set_student() 后面没有(也不能有const)。 

首先说一点题外话,为什么 get_name() 前面也加 const。如果没有前后两个 const 的话,get_name() 返回的是对私有数据成员 name 的引用,所以通过这个引用可以改变私有成员 name 的值,如 
  Student stu( "Wang", 85 );

  stu.get_name() = "Li";


即把 name 由原来的 "Wang" 变成了 "Li",而这不是我们希望的发生的。所以在 get_name() 前面加 const 避免这种情况的发生。 

那么,get_name() 和 get_score() 这两个后面应该加 const的成员函数,如果没有 const 修饰的话可不可以呢?回答是可以!但是这样做的代价是:const对象将不能再调用这两个非const成员函数了。如 
const string& get_name(); // 这两个函数都应该设成 const 型

int get_score();

void output_student( const Student& student ) 

{ 

  cout << student.get_name() << "\t"; // 如果 get_name() 和 get_score() 是非const成员函数,这一句和下一句调用是错误的

  cout << student.get_score() << endl; 

}


由于参数student表示的是一个对const Student型对象的引用,所以 student 不能调用非const成员函数如 set_student()。如果 get_name() 和 get_score() 成员函数也变成非const型,那么上面的 student.get_name() 和 student.get_score() 的使用就是非法的,这样就会给我们处理问题造成困难。 

因此,我们没有理由反对使用const,该加const时就应该加上const,这样使成员函数除了非const的对象之外,const对象也能够调用它。
<think>我们讨论的是成员函数后面const关键字的作用。 在C++中,成员函数后面加上const表示这个函数不会修改的成员变量(除了mutable修饰的成员)。这种函数称为常量成员函数。 主要作用: 1. 允许常量对象调用该函数。 2. 提高程序的安全性和清晰度(编译器会检查在const成员函数中是否修改了非mutable成员)。 3. 在重载函数时,const和非const版本可以同时存在,根据对象的常量性选择调用。 示例: 假设有一个MyArray,我们有一个访问元素的函数。我们可能希望常量对象和非常量对象都能访问元素,但常量对象返回常量引用,非常量对象返回非常量引用。 代码示例: </think>### 成员函数 `const` 的用途 在 C++ 中,函数声明后 `const` 关键字用于定义**常量成员函数**,其主要作用是保证该函数不会修改的成员变量(除了被声明为 `mutable` 的变量)。以下是详细解释和示例: #### 核心作用:对象状态保护 ```cpp class Counter { public: Counter() : count(0) {} // 非常量成员函数:可以修改成员 void increment() { count++; } // 常量成员函数:禁止修改成员 int getCount() const { return count; } // ❌ 若尝试修改:count = 5; 会触发编译错误 private: int count; }; ``` #### 关键特性解析 1. **常量对象访问权限** ```cpp const Counter c; // 常量对象 c.increment(); // ❌ 错误:常量对象只能调用const成员函数 int n = c.getCount(); // ✅ 正确:调用const成员函数 ``` 2. **函数重载依据** ```cpp class TextBuffer { std::string text; public: // 两个重载版本 char& charAt(size_t pos) { return text[pos]; // 返回可修改引用 } const char& charAt(size_t pos) const { return text[pos]; // 返回常量引用 } }; TextBuffer buf; const TextBuffer cbuf; buf.charAt(0) = 'A'; // 调用非常量版本 char c = cbuf.charAt(0); // 调用常量版本 ``` 3. **`mutable` 例外规则** ```cpp class Cache { mutable int accessCount; // 可被const函数修改 std::string data; public: std::string getData() const { accessCount++; // ✅ 允许修改mutable成员 return data; } }; ``` #### 完整使用示例 ```cpp #include <iostream> #include <string> class BankAccount { public: BankAccount(double b = 0) : balance(b) {} // 常量成员函数 double getBalance() const { // balance = 100; // ❌ 编译错误:禁止修改 return balance; } void deposit(double amount) { balance += amount; } // 重载的常量/非常量版本 const std::string& owner() const { return ownerName; } std::string& owner() { return ownerName; } private: double balance; std::string ownerName; }; int main() { BankAccount acc(1000); const BankAccount& accRef = acc; // 常量引用 // 常量对象操作 std::cout << "Balance: " << accRef.getBalance() << "\n"; // ✅ // accRef.deposit(100); // ❌ 错误:常量对象不能调用非常量函数 // 重载函数选择 acc.owner() = "Alice"; // 调用非常量版本(可修改) std::cout << "Owner: " << accRef.owner() << "\n"; // 调用常量版本 return 0; } ``` #### 设计价值和最佳实践 1. **安全保证**: - 防止意外修改对象状态 - 保证线程安全读取操作 2. **接口清晰化**: - 明确区分修改操作和查询操作 ```cpp class Vector { public: size_t size() const; // 查询 void push_back(int val); // 修改 }; ``` 3. **STL兼容**: - STL容器要求迭代器访问使用const迭代器时调用const成员函数 ```cpp const std::vector<int> vec{1,2,3}; auto it = vec.begin(); // 返回const_iterator ``` 4. **规则扩展**: - C++14起支持返回`auto`的const成员函数 ```cpp auto generateReport() const -> std::string; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值