类与实例
Coddy 面向 Rust 开发者的 C++ 课程的第 32 课,共 48 课。
Rust 结构体将数据与 impl 块分开。C++ 类会一起声明成员和方法,也可以在单独的文件中定义方法。C++ 对象可以直接作为值存储。成员函数作用于所属对象;类和结构体的区别在于默认访问权限。
Rust
fn main() {
struct Parcel { label: String, weight: i32 }
let parcel = Parcel { label: String::from("sample"), weight: 4 };
println!("{}", parcel.label);
assert_eq!(parcel.weight, 4);
}
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;std::string label()const{return "@"+name;}};
int main(){
Badge b{"Ada"};std::cout<<b.label()<<"\n";
}
分别跟踪每个程序。这些示例通过不同于任务的数据或操作来演示这个概念,不要假设源代码和目标代码的输出相同。
挑战
简单输入:整数宽度和高度,均为非负数。Rectangle 保存自身的尺寸,area 返回它们的乘积。驱动程序在测试中创建两个互相独立的对象。
可编辑模块:Rectangle.cpp、Rectangle.hpp。每个必需类型都有自己的命名头文件和实现文件。保留所有公共签名。锁定的 main.cpp 会读取标准输入,并直接调用 API。它也会在说明的情况下独立检查公共 API 的行为。在 API 中返回值,而不是打印结果。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "Rectangle.hpp"
#include <iostream>
int main(){
{Rectangle a(2,3),b(4,5);if(a.area()!=6||b.area()!=20||a.area()!=6)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 w,h;in>>w>>h;Rectangle r(w,h);std::cout<<r.area()<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 C++中的所有课
自己练习: C++ 在线编译器