实验2

一.实验任务1

1.问题1

屏幕截图 2025-10-28 181353

错误原因:

在task1.cpp的main函数中调用 func() 时,编译器需要看到函数的声明,如果去掉36行的语句,编译器无法找到 func() 的声明,导致错误

2.问题2

  1. T(int x = 0, int y = 0)

    • 功能:初始化对象,提供默认参数

    • 调用时机:创建新对象

  2. T(const T &t)

    • 功能:通过已有对象创建新对象,进行深拷贝

    • 调用时机:对象初始化时使用另一个对象

  3.  T(T &&t)

    • 功能:通过右值引用转移资源,避免不必要的拷贝

    • 调用时机:使用std::move

  4.  ~T()

    • 功能:,递减对象计数

    • 调用时机:自动调用

3.问题3

屏幕截图 2025-10-28 182021

错误原因:重复定义

 

二.实验任务二

#pragma once
#include <string>
#include <cmath>

class Complex {
private:
    double real;
    double imag;

public:
    // 静态常量成员
    static const std::string doc;
    
    // 构造函数
    Complex(double r = 0.0, double i = 0.0);
    Complex(const Complex& other);
    
    // 成员函数
    double get_real() const;
    double get_imag() const;
    void add(const Complex& other);
    
    // 友元函数声明
    friend void output(const Complex& c);
    friend double abs(const Complex& c);
    friend Complex add(const Complex& c1, const Complex& c2);
    friend bool is_equal(const Complex& c1, const Complex& c2);
    friend bool is_not_equal(const Complex& c1, const Complex& c2);
};
Complex.h
#include "Complex.h"
#include <iostream>
#include <iomanip>

// 静态成员初始化
const std::string Complex::doc = "a simplified complex class";

// 构造函数实现
Complex::Complex(double r, double i) : real(r), imag(i) {}

Complex::Complex(const Complex& other) : real(other.real), imag(other.imag) {}

// 成员函数实现
double Complex::get_real() const {
    return real;
}

double Complex::get_imag() const {
    return imag;
}

void Complex::add(const Complex& other) {
    real += other.real;
    imag += other.imag;
}

// 友元函数实现
void output(const Complex& c) {
    std::cout << c.real;
    if (c.imag >= 0) {
        std::cout << " + " << c.imag << "i";
    } else {
        std::cout << " - " << -c.imag << "i";
    }
}

double abs(const Complex& c) {
    return std::sqrt(c.real * c.real + c.imag * c.imag);
}

Complex add(const Complex& c1, const Complex& c2) {
    return Complex(c1.real + c2.real, c1.imag + c2.imag);
}

bool is_equal(const Complex& c1, const Complex& c2) {
    return c1.real == c2.real && c1.imag == c2.imag;
}

bool is_not_equal(const Complex& c1, const Complex& c2) {
    return !is_equal(c1, c2);
}
Complex.cpp
#include "Complex.h"
#include <iostream>
#include <iomanip>
#include <complex>

void test_Complex();
void test_std_complex();

int main() {
    std::cout << "*******测试1: 自定义类Complex*******\n";
    test_Complex();
    std::cout << "\n*******测试2: 标准库模板类complex*******\n";
    test_std_complex();
}

void test_Complex() {
    using std::cout;
    using std::endl;
    using std::boolalpha;
    
    cout << "类成员测试: " << endl;
    cout << Complex::doc << endl << endl;
    
    cout << "Complex对象测试: " << endl;
    Complex c1;
    Complex c2(3, -4);
    Complex c3(c2);
    Complex c4 = c2;
    const Complex c5(3.5);
    
    cout << "c1 = "; output(c1); cout << endl;
    cout << "c2 = "; output(c2); cout << endl;
    cout << "c3 = "; output(c3); cout << endl;
    cout << "c4 = "; output(c4); cout << endl;
    cout << "c5.real = " << c5.get_real() 
         << ", c5.imag = " << c5.get_imag() << endl << endl;
    
    cout << "复数运算测试: " << endl;
    cout << "abs(c2) = " << abs(c2) << endl;
    c1.add(c2);
    cout << "c1 += c2, c1 = "; output(c1); cout << endl;
    cout << boolalpha;
    cout << "c1 == c2 : " << is_equal(c1, c2) << endl;
    cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl;
    c4 = add(c2, c3);
    cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl;
}

void test_std_complex() {
    using std::cout;
    using std::endl;
    using std::boolalpha;
    
    cout << "std::complex<double>对象测试: " << endl;
    std::complex<double> c1;
    std::complex<double> c2(3, -4);
    std::complex<double> c3(c2);
    std::complex<double> c4 = c2;
    const std::complex<double> c5(3.5);
    
    cout << "c1 = " << c1 << endl;
    cout << "c2 = " << c2 << endl;
    cout << "c3 = " << c3 << endl;
    cout << "c4 = " << c4 << endl;
    cout << "c5.real = " << c5.real() 
         << ", c5.imag = " << c5.imag() << endl << endl;
    
    cout << "复数运算测试: " << endl;
    cout << "abs(c2) = " << abs(c2) << endl;
    c1 += c2;
    cout << "c1 += c2, c1 = " << c1 << endl;
    cout << boolalpha;
    cout << "c1 == c2 : " << (c1 == c2) << endl;
    cout << "c1 != c2 : " << (c1 != c2) << endl;
    c4 = c2 + c3;
    cout << "c4 = c2 + c3, c4 = " << c4 << endl;
}
task2.cpp

屏幕截图 2025-10-28 195031

1.问题1:后者更简洁;有关联

2.问题2

   2-1:否;可以通过类的公有接口实现,不需要直接访问私有数据

   2-2:标准库std::complex没有把abs设为友元

   2-3:需要访问类的私有成员,且无法通过公有接口完成时;

            类需要互相访问对方私有成员时。

3.问题3:代码改为

class Complex {
 ...
explicit Complex(const Complex& other);
...
};

 

三.实验任务三

#pragma once
#include <string>

enum class ControlType {Play, Pause, Next, Prev, Stop, Unknown};

class PlayerControl {
public:
    PlayerControl();
    
    static int get_cnt();
    ControlType parse(const std::string& control_str);  
    void execute(ControlType cmd) const;          
    
private:
    static int total_cnt;   
};
PlayerControl.h
#include "PlayerControl.h"
#include <iostream>
#include <algorithm>
#include <cctype>

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

ControlType PlayerControl::parse(const std::string& control_str) {
    // 1. 将输入字符串转为小写,实现大小写不敏感
    std::string lower_str = control_str;
    std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(),
                   [](unsigned char c) { return std::tolower(c); });
    
    ControlType result = ControlType::Unknown;
    
    // 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举
    if (lower_str == "play") {
        result = ControlType::Play;
    } else if (lower_str == "pause") {
        result = ControlType::Pause;
    } else if (lower_str == "next") {
        result = ControlType::Next;
    } else if (lower_str == "prev") {
        result = ControlType::Prev;
    } else if (lower_str == "stop") {
        result = ControlType::Stop;
    } else {
        result = ControlType::Unknown;
    }
    
    // 4. 每次成功调用parse时递增total_cnt
    if (result != ControlType::Unknown) {
        total_cnt++;
    }
    
    return result;
}

void PlayerControl::execute(ControlType cmd) const {
    switch (cmd) {
    case ControlType::Play:  std::cout << "[play] Playing music...\n"; break;
    case ControlType::Pause: std::cout << "[Pause] Music paused\n";    break;
    case ControlType::Next:  std::cout << "[Next] Skipping to next track\n"; break;
    case ControlType::Prev:  std::cout << "[Prev] Back to previous track\n"; break;
    case ControlType::Stop:  std::cout << "[Stop] Music stopped\n"; break;
    default:                 std::cout << "[Error] unknown control\n"; break;
    }
}

int PlayerControl::get_cnt() {
    return total_cnt;
}
PlayerControl.cpp
#include "PlayerControl.h"
#include <iostream>

void test() {
    PlayerControl controller;
    std::string control_str;
    std::cout << "Enter Control: (play/pause/next/prev/stop/quit):\n";
    
    while(std::cin >> control_str) {
        if(control_str == "quit")
            break;
        
        ControlType cmd = controller.parse(control_str);
        controller.execute(cmd);
        std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n";
    }
}

int main() {
    test();
    return 0;
}
task3.cpp

屏幕截图 2025-10-28 200257

 

四.实验任务四

#pragma once
#include <string>

class Fraction {
private:
    int up;     // 分子
    int down;   // 分母
    
    // 内部工具函数
    void simplify();           // 分数化简
    int gcd(int a, int b) const; // 求最大公约数
    
public:
    // 静态常量成员
    static const std::string doc;
    
    // 构造函数
    Fraction(int numerator = 0, int denominator = 1);
    Fraction(const Fraction& other);
    
    // 成员函数
    int get_up() const;
    int get_down() const;
    Fraction negative() const;
    
    // 友元函数声明
    friend void output(const Fraction& f);
    friend Fraction add(const Fraction& f1, const Fraction& f2);
    friend Fraction sub(const Fraction& f1, const Fraction& f2);
    friend Fraction mul(const Fraction& f1, const Fraction& f2);
    friend Fraction div(const Fraction& f1, const Fraction& f2);
};
Fraction.h
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <cmath>

// 静态成员初始化
const std::string Fraction::doc = "Fraction类 v 0.01版. 目前仅支持分数对象的构造、输出、加/减/乘/除运算.";

// 求最大公约数
int Fraction::gcd(int a, int b) const {
    a = std::abs(a);
    b = std::abs(b);
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

// 分数化简
void Fraction::simplify() {
    if (down == 0) {
        throw std::runtime_error("分母不能为0");
    }
    
    // 处理符号
    if (down < 0) {
        up = -up;
        down = -down;
    }
    
    // 约分
    int common_divisor = gcd(up, down);
    if (common_divisor != 0) {
        up /= common_divisor;
        down /= common_divisor;
    }
}

// 构造函数
Fraction::Fraction(int numerator, int denominator) : up(numerator), down(denominator) {
    simplify();
}

Fraction::Fraction(const Fraction& other) : up(other.up), down(other.down) {}

// 成员函数实现
int Fraction::get_up() const {
    return up;
}

int Fraction::get_down() const {
    return down;
}

Fraction Fraction::negative() const {
    return Fraction(-up, down);
}

// 友元函数实现
void output(const Fraction& f) {
    std::cout << f.up;
    if (f.down != 1) {
        std::cout << "/" << f.down;
    }
}

Fraction add(const Fraction& f1, const Fraction& f2) {
    int new_up = f1.up * f2.down + f2.up * f1.down;
    int new_down = f1.down * f2.down;
    return Fraction(new_up, new_down);
}

Fraction sub(const Fraction& f1, const Fraction& f2) {
    int new_up = f1.up * f2.down - f2.up * f1.down;
    int new_down = f1.down * f2.down;
    return Fraction(new_up, new_down);
}

Fraction mul(const Fraction& f1, const Fraction& f2) {
    int new_up = f1.up * f2.up;
    int new_down = f1.down * f2.down;
    return Fraction(new_up, new_down);
}

Fraction div(const Fraction& f1, const Fraction& f2) {
    if (f2.up == 0) {
        throw std::runtime_error("除数不能为0");
    }
    int new_up = f1.up * f2.down;
    int new_down = f1.down * f2.up;
    return Fraction(new_up, new_down);
}
Fraction.cpp
#include "Fraction.h"
#include <iostream>

void test1();
void test2();

int main() {
    std::cout << "测试1: Fraction类基础功能测试\n";
    test1();
    std::cout << "\n测试2: 分母为0测试: \n";
    test2();
}

void test1() {
    using std::cout;
    using std::endl;   
    
    cout << "Fraction类测试: " << endl;
    cout << Fraction::doc << endl << endl;
    
    Fraction f1(5);
    Fraction f2(3, -4), f3(-18, 12);
    Fraction f4(f3);
    
    cout << "f1 = "; output(f1); cout << endl;
    cout << "f2 = "; output(f2); cout << endl;
    cout << "f3 = "; output(f3); cout << endl;
    cout << "f4 = "; output(f4); cout << endl;
    
    const Fraction f5(f4.negative());
    cout << "f5 = "; output(f5); cout << endl;
    cout << "f5.get_up() = " << f5.get_up() 
         << ", f5.get_down() = " << f5.get_down() << endl;
    
    cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl;
    cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl;
    cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl;
    cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl;
    cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl;
}

void test2() {
    using std::cout;
    using std::endl;
    
    Fraction f6(42, 55), f7(0, 3);
    cout << "f6 = "; output(f6); cout << endl;
    cout << "f7 = "; output(f7); cout << endl;
    
    try {
        cout << "f6 / f7 = "; output(div(f6, f7)); cout << endl;
    } catch (const std::exception& e) {
        std::cout << "错误: " << e.what() << std::endl;
    }
}
task4.cpp

屏幕截图 2025-10-28 201207

我选的是友元函数

优点是能够直接访问私有成员,减少性能开销

缺点是破坏了封装性

posted @ 2025-10-28 20:14  崎膺  阅读(2)  评论(0)    收藏  举报