类与实例
Coddy 面向 C# 开发者的 C++ 课程的第 32 课,共 48 课。
C# 区分值类型结构体和引用类型类。C++ 的 class 和 struct 都支持值对象。C++ 对象可以直接作为值存储。成员函数作用于所属对象;class 和 struct 的默认访问权限不同。
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Item { public string Name; public Item(string name) { Name=name; } }
static void Main() {
Console.WriteLine(new Item("pen").Name);
}
}
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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 C++中的所有课
自己练习: C++ 在线编译器