2.

2.#

警告

以下内容考试中是用英文写在纸上, 也就是代码需要自己抄一遍到电脑里, 所以 要学会正确使用键盘, 加快打字速度!

Please complete the program while keeping interfaces and implementations seperated.

The program implements a class called List, which can store any number of std::string objects, and satisfies the following invariants,

  • std::string* data_

    • The member that holds all std::string objects.

  • int size_

    • The member that indicates the amount of std::string objects; if no object exists, size_ == 0.

  • Element uniqueness

    • For any two different objects string1 and string2 holded by data_, string1 == string2 (equality) should not be true.

    • Also, when inserting a new object, the insertion should not happen if there's already an equal object.

You should implement the following functions for it,

  • Constructor List(std::string* data, int size)

    • Insert all elements inside [data, data + size) into data_.

  • Copy constructor

  • Copy assignment

  • auto operator+=(List const& other) -> List&

    • Insert all elements inside other into *this.

  • friend auto operator+(List const& lhs, List const& rhs) -> List

    • Merge two List as a List.

  • friend auto operator<<(std::ostream& ostream, List const& list) -> std::ostream&

    • Output the stored std::string objects with the format [element_1, element_2, ..., element_n].

The following has given part of the List's implementation and the main() function.

my_list.hpp#
 1#ifndef MY_LIST_HPP
 2#define MY_LIST_HPP
 3
 4#include <iosfwd>
 5#include <string>
 6/* 你可以添加任意标准库头文件 */
 7
 8class MyList {
 9 public:
10  // 请补充
11
12 private:
13  std::string* data_;
14  int size_;
15};
16
17#endif
main.cpp#
 1#include "my_list.hpp"
 2
 3#include <iostream>
 4#include <string>
 5
 6auto main() -> int {
 7  std::string s1[] = {"John", "Bat-man", "Doctor", "John"};
 8  std::string s2[] = {"Doctor", "Smith", "Komeji", "Smith"};
 9  std::string s3[] = {"Komeji", "Satori", "Momo", "Satori"};
10
11  MyList list1(s1, 4);
12  MyList list2(s2, 4);
13  MyList list3;
14
15  std::cout << list1 << '\n';
16  std::cout << list2 << '\n';
17  std::cout << list3 << '\n';
18
19  list3  = list2;
20  list1 += list2;
21  list1  = list1 + list3;
22
23  std::cout << list1 << '\n';
24  std::cout << list2 << '\n';
25  std::cout << list3 << '\n';
26}