Menu
CoddyTech

类与实例

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

Ruby 对象始终通过引用访问,而且实例变量没有预先声明:每个 @variable 都会在首次赋值时创建,因此同一个类的两个对象可以拥有不同的变量集合。C++ 对象的布局和取值行为在编译时声明。C++ 对象可以直接作为值存储。成员函数对其所属对象进行操作;类和结构体的默认访问权限不同。

Ruby

class Parcel
  attr_accessor :label
end
parcel = Parcel.new
parcel.label = "sample"
parcel.instance_variable_set(:@weight, 4)
puts parcel.label
p parcel.instance_variables

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自我测试

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

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

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