方法与 const 访问
Coddy 面向 Java 开发者的 C++ 课程的第 34 课,共 48 课。
Java 没有直接对应的 const 成员函数限定符。final 引用并不意味着被引用的对象是只读的。C++ 实例方法会隐式接收 this。可以通过 const 引用调用 const 成员函数。
Java
import java.util.*;
public class Example {
static class Badge {String name;Badge(String n){name=n;}void rename(String n){name=n;}String label(){return name;}}
public static void main(String[] args) {
Badge b=new Badge("old");b.rename("new");System.out.println(b.label());
}
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Badge {std::string name;void rename(std::string n){name=std::move(n);}std::string label()const{return name;}};
int main(){
Badge b{"old"};b.rename("new");const Badge& r=b;std::cout<<r.label()<<"\n";
}
分别跟踪每个程序。这些示例通过使用与任务中不同的操作或数据来演示这个概念,不要假设源代码和目标代码的输出相同。
挑战
简单输入:初始值和两个带符号的变化量。Counter.add 会修改实例;value 是 const,并返回实例的当前状态。
可编辑模块:Counter.cpp、Counter.hpp。每种必需类型都有各自命名的头文件和实现文件。保留所有公共签名。锁定的 main.cpp 会读取 stdin 并直接调用 API。题目另有说明时,它也会独立检查公共 API 的行为。在 API 内返回值,不要打印。整数输入和结果都在 signed int 范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "Counter.hpp"
#include <iostream>
int main(){
{Counter a(2),b(9);a.add(5);const Counter& r=a;if(r.value()!=7||b.value()!=9)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n,a,b;in>>n>>a>>b;Counter c(n);c.add(a);c.add(b);std::cout<<c.value()<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Java 开发者的 C++中的所有课
自己练习: C++ 在线编译器