类与实例
Coddy 面向 Python 开发者的 C++ 课程的第 32 课,共 48 课。
Python 类的实例是通过引用访问的对象,具有灵活的属性。C++ 对象的布局和行为在编译时声明。C++ 对象可以直接作为值存储。成员函数作用于所属对象;类和结构体的默认访问权限不同。
Python
class Parcel:
pass
parcel = Parcel()
parcel.label = "sample"
parcel.weight = 4
print(parcel.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;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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 C++中的所有课
自己练习: C++ 在线编译器