Menu
CoddyTech

类与实例

Coddy 面向 Swift 开发者的 C++ 课程的第 32 课,共 48 课。

Swift 会在 struct 或 class 中一起声明存储属性和方法,并为结构体自动生成成员逐一初始化器。C++ 类也会一起声明成员和方法,但可以在单独的文件中定义方法。无论使用哪个关键字声明,C++ 对象都会直接作为值存储:不像 Swift 那样有引用类型的类。成员函数会对其所属对象进行操作;类和结构体的区别仅在于默认访问权限。

Swift

struct Parcel {
    let label: String
    var weight: Int
    func summary() -> String { "\(label) weighs \(weight)" }
}
let parcel = Parcel(label: "sample", weight: 4)
print(parcel.summary())

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";
}

分别跟踪每个程序。这些示例通过不同于任务中的操作或数据来演示这一概念,不应假设源代码和目标代码的输出相同。

challenge icon

挑战

简单

输入:非负整数 width 和 height。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";
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Swift 开发者的 C++中的所有课

自己练习: C++ 在线编译器