|
发表于 2021-6-20 20:04:05
|
显示全部楼层
本楼为最佳答案
 - #include <iostream>
- #include <cctype>
- class complex_t {
- public:
- complex_t(double real, double imag = 0): real(real), imag(imag) {}
- complex_t(): complex_t(0, 0) {}
- friend std::istream &operator>>(std::istream &is, complex_t &rhs) {
- is >>rhs.real >> rhs.imag;
- if(is.get() != 'i') {
- is.unget();
- std::cerr << "invalid input" << std::endl;
- return is;
- }
- if(!std::isspace(is.get())) {
- is.unget();
- std::cerr << "invalid input" << std::endl;
- return is;
- }
- return is;
- }
- friend std::ostream &operator<<(std::ostream &os, const complex_t &rhs) {
- const auto flags = os.flags();
- os << std::noshowpos << rhs.real << std::showpos << rhs.imag << "i";
- os.flags(flags);
- return os;
- }
- friend const complex_t operator+(const complex_t &lhs, const complex_t &rhs) {
- return complex_t(lhs.real + rhs.real, lhs.imag + rhs.imag);
- }
- private:
- double real, imag;
- };
- int main() {
- {
- complex_t a;
- std::cout << a << std::endl;
- }
- {
- complex_t a(3);
- std::cout << a << std::endl;
- }
- {
- complex_t a(3, 4);
- std::cout << a << std::endl;
- }
- {
- complex_t a(3, 4), b(2, -7);
- std::cout << a << ' ' << b << std::endl;
- }
- {
- complex_t a(3, 4), b(2, -7);
- complex_t c = a + b;
- std::cout << c << std::endl;
- }
- {
- complex_t a(3, 4), b(2, -7), c(-1, 8);
- complex_t d = a + b + c;
- std::cout << d << std::endl;
- }
- {
- complex_t a;
- std::cin >> a;
- std::cout << a << std::endl;
- }
- {
- complex_t a, b;
- std::cin >> a >> b;
- std::cout << a << ' ' << b << std::endl;
- }
- return 0;
- }
复制代码 |
|