构造函数初始化
Coddy 面向 Java 开发者的 C++ 课程的第 33 课,共 48 课。
Java 构造函数会初始化字段,而 C++ 还会按声明顺序初始化其中包含的值对象。C++ 构造函数会建立不变量。成员初始化列表用于初始化字段,实际初始化顺序则遵循成员声明顺序。
Java
import java.util.*;
public class Example {
static class Bag { List<Integer> items=new ArrayList<>(); }
public static void main(String[] args) {
Bag a=new Bag(),b=new Bag(); a.items.add(1); System.out.println(b.items.size());
}
}
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;explicit Badge(std::string n):name(std::move(n)){} };
int main(){
Badge b("Ada");std::cout<<b.name<<"\n";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示这一概念,不要假设源代码和目标代码的输出相同。
挑战
简单输入:初始余额为整数,存款金额为非负数。Wallet 会将余额初始化为 max(start,0);add 会增加余额;balance 会返回当前金额。
可编辑模块:Wallet.cpp、Wallet.hpp。每种必需类型都有各自命名的头文件和实现文件。保留所有公共签名。锁定的 main.cpp 会读取 stdin 并直接调用 API。它还会在说明中指出的地方独立检查公共 API 的行为。在 API 内返回值,而不是打印值。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "Wallet.hpp"
#include <iostream>
int main(){
{Wallet a(-2),b(7);a.add(3);a.add(4);if(a.balance()!=7||b.balance()!=7)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 n,d;in>>n>>d;Wallet w(n);w.add(d);std::cout<<w.balance()<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Java 开发者的 C++中的所有课
自己练习: C++ 在线编译器