任务一

一、源代码

//t.h
#pragma once
#include <string>
class T {
public:
    T(int x = 0, int y = 0); 
    T(const T &t);  
    T(T &&t);       
    ~T();           
    void adjust(int ratio);     
    static int get_cnt();    
    friend void output(const T &t);
    static const std::string doc;   
    static const int MAX_CNT;           
private:
    int m1, m2; 
    static int current_cnt; 
};
//t.h
#pragma once
#include <string>
class T {
public:
    T(int x = 0, int y = 0); 
    T(const T &t);  
    T(T &&t);       
    ~T();           
    void adjust(int ratio);     
    static int get_cnt();    
    friend void output(const T &t);
    static const std::string doc;   
    static const int MAX_CNT;           
private:
    int m1, m2; 
    static int current_cnt; 
};
//t.cpp
#include "t.h"
#include <iostream>
#include <stdexcept>
#include <string>

const std::string T::doc{"a simple class sample"};
const int T::MAX_CNT = 999;
int T::current_cnt = 0;

T::T(int x, int y): m1{x}, m2{y} { 
    if(current_cnt == MAX_CNT) {
        throw std::runtime_error("T: maximum object count exceeded");
    }
    ++current_cnt; 
    std::cout << "T constructor called.\n";
} 

T::T(const T &t): m1{t.m1}, m2{t.m2} {
    if(current_cnt == MAX_CNT) {
        throw std::runtime_error("T: maximum object count exceeded");
    }
    ++current_cnt;
    std::cout << "T copy constructor called.\n";
}

T::T(T &&t): m1{t.m1}, m2{t.m2} {
    if(current_cnt == MAX_CNT) {
        throw std::runtime_error("T: maximum object count exceeded");
    }
    ++current_cnt;
    std::cout << "T move constructor called.\n";
}    

T::~T() {
    --current_cnt;
    std::cout << "T destructor called.\n";
}           

void T::adjust(int ratio) {
    m1 *= ratio;
    m2 *= ratio;
}      

int T::get_cnt() {
   return current_cnt;
}
void output(const T &t) {
    std::cout << "(" << t.m1 << ", " << t.m2 << ")";
}
//task1.cpp
#include <iostream>
#include <utility>
#include "t.h"
void test() {
    using std::cout;
    using std::endl;
    cout << "T info: " << T::doc << endl;
    cout << "T objects'max count: " << T::MAX_CNT << endl;
    cout << "T objects'current count: " << T::get_cnt() << endl << endl;
    {
        T t1;
        cout << "t1 = "; output(t1); cout << endl;
        T t2(3, 4);
        cout << "t2 = "; output(t2); cout << endl;
        T t3(t2);
        t3.adjust(2);
        cout << "t3 = "; output(t3); cout << endl;
        T t4(std::move(t2));
        cout << "t4 = "; output(t4); cout << endl;
        cout << "test: T objects'current count: " << T::get_cnt() << endl;
    }
    cout << "test: T objects'current count: " << T::get_cnt() << endl;
}
int main() {
    std::cout << "test Class T: \n";
    test();
}

二、运行结果

task1、1

三、回答问题

问题一:

  • T(int x=0,int y=0)普通构造函数:创建新对象,初始化成员m1,m2;定义对象、不带拷贝移动时调用。t1、t2触发普通构造。
  • T(const T &t)拷贝构造函数:用已有对象复制生成新对象;对象拷贝、传值、返回对象调用。t3触发拷贝构造。
  • T(T&& t)移动构造函数:接管临时/右值对象资源,std::move强制转为右值时调用。t4触发移动构造。
  • ~T()析构函数:对象销毁前释放资源,对象离开作用域自动调用。

问题二:

  • 能正常运行

问题三:

  • t1、t2、t3、t4作用域为内层大括号{ ... };生命周期从定义处到大括号结束,出大括号对象销毁。
  • t1不能直接访问私有m1、m2。体现类的封装特性:private私有成员仅类内部/友元可以访问,外部被隐藏保护。

问题四:

  • throw 是C++异常抛出关键字,用于主动抛出一个异常对象,中断当前正常代码执行流程,去寻找匹配的catch捕获块。
  • 能正常运行

image

  • 不知道。询问AI,AI给出的解释是当执行throw抛出异常,且代码没有try‑catch捕获时,会发生栈展开(stack unwinding):异常从当前函数向外逐层回退函数调用栈。在栈展开过程中,局部作用域内已经完整构造完毕的栈对象,会自动调用析构函数完成销毁。t1已经执行完构造函数,属于完全构造成功的局部对象,因此会调用析构。

任务二

一、源代码

//Complex.h
#pragma once
#include <string>
class Complex
{
public:
    static const std::string doc;
    Complex();
    Complex(double r);
    Complex(double r, double i);
    Complex(const Complex& other);

    double real() const;
    double 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);
private:
    double real_;
    double imag_;
};
//Complex.cpp
#include "Complex.h"
#include <iostream>
#include <cmath>

const std::string Complex::doc{"a simplified complex class"};

Complex::Complex():real_(0),imag_(0){}
Complex::Complex(double r):real_(r),imag_(0){}
Complex::Complex(double r, double i):real_(r),imag_(i){}
Complex::Complex(const Complex& other):real_(other.real_), imag_(other.imag_){}

double Complex::real() const{ return real_; }
double Complex::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);
}
//task2.cpp
#include <iomanip>
#include <iostream>
#include <complex>

#include "Complex.h"

// 测试自定义类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);
    const Complex c6 = 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 = "; output(c5); cout << endl;
    cout << "c6.real = " << c6.real() 
         << ", c6.imag = " << c6.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;
}

// 测试标准库类模板complex
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;
    std::complex<double> c5 = 3.5;
    const std::complex<double> c6(3.5);

    cout << "c1 = " << c1 << endl;
    cout << "c2 = " << c2 << endl;
    cout << "c3 = " << c3 << endl;
    cout << "c4 = " << c4 << endl;
    cout << "c5 = " << c5 << endl;

    cout << "c6.real = " << c6.real() 
         << ", c6.imag = " << c6.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;
}

int main() {
    std::cout << "*******测试1: 自定义类Complex*******\n";
    test_Complex();

    std::cout << "\n*******测试2: 标准库类模板complex*******\n";
    test_std_complex();
}

二、运行结果

image

三、回答问题

问题一:

  • 加const。const对象不能调用非const函数,编译器会报错:passing 'const Complex' as 'this' argument discards qualifiers
  • 不能。因为 c6 是 const 对象,而 add 是会修改对象。体现了类的 const 保护机制,保证了 const 的对象在初始化后不能被修改。

问题二:

  • 标准库使用运算符重载(+、==、!=),本质上底层仍然是函数,只是语法更简洁好看

问题三:

  • 友元不是必须的。可以写成普通非成员函数,不使用 friend。
    实现思路:调用类中已有的公有接口 real()、imag() 获取实部和虚部,再完成运算、输出等操作,不需要直接访问私有成员 real_、imag_。
  • std::complex 的 abs 不是友元函数,它属于独立的非成员模板函数,通过公有接口获取数据进行计算。
    链接:https://en.cppreference.com/w/cpp/numeric/complex/abs
  • 工业开发优先依靠公有接口,尽量不用friend。仅在函数逻辑不属于类本身,但又需要频繁访问私有成员(如运算符重载),或者多个紧密耦合的类协作、测试需要访问内部数据时才考虑。使用时要谨慎,因为它会破坏封装,增加耦合,不利于后期维护,能使用公有接口就优先不用friend。

任务三

一、源代码

//PlayerControl.h
#pragma once
#include <string>
enum class ControlType {Play, Pause, Next, Prev, Stop, Unknown};
class PlayerControl {
public:
    PlayerControl();
    ControlType parse(const std::string& control_str);
    void execute(ControlType cmd) const;
    static int get_cnt();
private:
    static int total_cnt;
};
//PlayerControl.cpp
#include "PlayerControl.h"
#include <algorithm>
#include <iostream>

int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}

ControlType PlayerControl::parse(const std::string& control_str)
{
    std::string s = control_str;
    //转小写
    for(auto &ch : s){
        ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
    }
    if(s == "play") return ControlType::Play;
    if(s == "pause") return ControlType::Pause;
    if(s == "next") return ControlType::Next;
    if(s == "prev") return ControlType::Prev;
    if(s == "stop") return ControlType::Stop;
    return ControlType::Unknown;
}

void PlayerControl::execute(ControlType cmd) const
{
    ++total_cnt;
    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;
}
//task3.cpp
#include <iostream>

#include "PlayerControl.h"

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();
}

二、运行结果

image

三、回答问题

问题:

  • const 成员函数的作用是:不能修改本对象的普通非静态成员变量。
  • total_cnt 是 static 静态成员,属于整个类,不属于某个对象实例,不受对象层面 const 的限制。因此,即使函数是 const,也可以修改它。

任务四

一、源代码

//Fraction.h
#pragma once
#include <string>
class Fraction
{
public:
    static const std::string doc;
    Fraction(int up0);
    Fraction(int up0, int down0);
    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);

private:
    int up;
    int down;
    void simplify(); //约分内部工具
    static int gcd(int a, int b);
};
//Fraction.cpp
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <algorithm>

const std::string Fraction::doc{R"(Fraction类 v 0.01版.
目前仅支持分数对象的构造、输出、加/减/乘/除运算.)"};

static int abs_int(int x){ return x<0 ? -x : x; }
int Fraction::gcd(int a, int b)
{
    a = abs_int(a);
    b = abs_int(b);
    while(b !=0 ){
        int t = a%b;
        a = b;
        b = t;
    }
    return a;
}

void Fraction::simplify()
{
    if(down ==0) throw std::invalid_argument("Fraction: 分母不能为0");
    if(down < 0){
        up = -up;
        down = -down;
    }
    int g = gcd(up, down);
    if(g != 0){
        up /= g;
        down /= g;
    }
    if(up ==0){
        down = 1;
    }
}

Fraction::Fraction(int up0):up{up0}, down{1}{ simplify(); }

Fraction::Fraction(int up0, int down0): up{up0}, down{down0}
{
    if(down0 == 0) throw std::invalid_argument("Fraction: 分母不能为0");
    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)
{
    if(f.down == 1){
        std::cout << f.up;
    }else{
        std::cout << f.up << "/" << 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::invalid_argument("Fraction: 分母不能为0");
    int new_up = f1.up * f2.down;
    int new_down = f1.down * f2.up;
    return Fraction(new_up, new_down);
}
//task4.cpp
#include <iostream>

#include "Fraction.h"

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;
    cout << "f6 / f7 = "; output(div(f6, f7)); cout << endl;
}

int main() {
    std::cout << "测试1: Fraction类基础功能测试\n";
    test1();

    std::cout << "\n测试2: 分母为0测试: \n";
    test2();
}

二、运行结果

image

三、回答问题

问题:

  • 选择方案1(分数类 + 友元函数)。
  • 理由:友元函数可以直接访问类的私有分子、分母,代码写起来更简便,不用反复调用getter函数。适合本实验,运算逻辑和类紧密相关,读写私有成员更高效。
posted on 2026-11-20 00:49  lamm40  阅读(0)  评论(0)    收藏  举报