实验2

任务一

  • 源代码

t.cpp

点击查看代码
#include "t.h"

#include <iostream>
#include <stdexcept>
#include <string>

// static³ÉÔ±Êý¾Ý: ÀàÄÚÉùÃ÷¡¢ÀàÍâ³õʼ»¯
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) {

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();          // ÏÔʾµ±Ç°TÀà¶ÔÏó×ÜÊý

    friend void output(const T &t); // ÓÑÔª, ÒÔ(m1, m2)ÐÎʽÊä³ö¶ÔÏót

    static const std::string doc;       // ÀàTµÄÃèÊöÐÅÏ¢
    static const int MAX_CNT;           // ÀàT¶ÔÏóÉÏÏÞ

private:
    int m1, m2;  // ¶ÔÏóÊý¾Ý³ÉÔ±

    static int current_cnt;    // µ±Ç°TÀà¶ÔÏóÊýÄ¿
};

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();
}
  • 运行截图

屏幕截图 2026-11-19 182213

  • 问题

line7 T(int x=0,int y=0)是普通构造函数;功能是创建新对象,初始化成员;调用时机是显性创建一个对象,隐性创建一个临时对象时;t1、t2调用了普通构造。
line8 T(const T &t)是复制构造函数;功能是用已有对象副本创建新对象;调用时机是用对象初始化一个新对象,对象作为函数形参,对象作为函数返回值时;t3调用了复制构造。
line9 T(T&& t)是移动构造函数;功能是接管临时或右值对象资源;调用时机是用对象初始化一个新对象,对象作为函数形参,对象作为函数返回值时;t4调用了移动构造。
line10 ~T()是析构函数;功能是销毁对象,释放资源;调用时机是对象离开作用域或delete 时。
2.
可以

屏幕截图 2026-11-19 183934
3.
t1‑t4作用域为大括号内部;生命周期从定义处到大括号结束。
t1不能直接访问私有m1、m2。体现了类的封装特性,private私有成员对外隐藏,外部只能通过public接口访问。
4.
throw抛出 C++ 异常对象,终止正常执行,向上寻找catch;本代码无 catch 捕获异常。

屏幕截图 2026-11-19 184903
崩溃终止
会被正常销毁。因为栈展开机制,异常抛出,栈上已经构造完成的局部对象,会自动调用析构函数释放,再程序终止。

任务二

  • 源代码

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

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 &a, const Complex &b);
    friend bool is_equal(const Complex &a, const Complex &b);
    friend bool is_not_equal(const Complex &a, const Complex &b);

private:
    double m_real;
    double m_imag;
};

Complex.cpp

点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>

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

Complex::Complex():m_real(0),m_imag(0){}
Complex::Complex(double r):m_real(r),m_imag(0){}
Complex::Complex(double r, double i):m_real(r),m_imag(i){}
Complex::Complex(const Complex& other){
    m_real = other.m_real;
    m_imag = other.m_imag;
}

double Complex::real() const{
    return m_real;
}
double Complex::imag() const{
    return m_imag;
}

void Complex::add(const Complex& other){
    m_real += other.m_real;
    m_imag += other.m_imag;
}

void output(const Complex &c){
    std::cout << c.m_real;
    if(c.m_imag >= 0) std::cout << "+";
    std::cout << c.m_imag << "i";
}

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

Complex add(const Complex &a, const Complex &b){
    return Complex(a.m_real+b.m_real, a.m_imag+b.m_imag);
}

bool is_equal(const Complex &a, const Complex &b){
    return a.m_real == b.m_real && a.m_imag == b.m_imag;
}
bool is_not_equal(const Complex &a, const Complex &b){
    return !is_equal(a,b);
}
  • 运行截图

屏幕截图 2026-11-19 185537

  • 问题

必须加const关键字。不加的话编译器会报错 “不能调用非 const 成员函数”。
不能编译通过。因为add()会修改对象,是普通非 const 成员,而const对象禁止调用会修改自身状态的成员。这体现了const对象只读保护机制。
2.
标准库模板类complex形式更简洁.
自定义是普通函数,标准库是运算符重载。二者内在逻辑等价。
3.
不是必须。可以增加public get 接口real(),imag()。
标准库std::complex不把abs设为友元。链接https://en.cppreference.com/cpp/numeric/complex/abs
friend 使用场景:需要访问私有成员,又不适合作为成员函数;需要高效,不想增加大量 get 接口;运算符重载少数场景。尽量少用,破坏封装。

任务三

  • 源代码

PlayControl.cpp

点击查看代码
#include "PlayerControl.h"

#include <algorithm>  
#include <iostream>

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

// ´ý²¹×ã
// 1. ½«ÊäÈë×Ö·û´®Í³Ò»³ÉתΪСд£¬ÊµÏÖ´óСд²»Ãô¸Ð
// 2. Æ¥Åä"play"/"pause"/"next"/"prev"/"stop"²¢·µ»Ø¶ÔӦö¾Ù;
//    δƥÅäµÄ×Ö·û´®·µ»ØControlType::Unknown
ControlType PlayerControl::parse(const std::string& control_str) {
    std::string s = control_str;
    std::transform(s.begin(), s.end(), s.begin(),
        [](unsigned char ch){ return static_cast<unsigned char>(tolower(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×ÔÔö 1
    ++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;
}

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);   // ʵÏÖstd::string --> ControlTypeת»»
    void execute(ControlType cmd) const;   // Ö´ÐпØÖƲÙ×÷£¨ÒÔ´òÓ¡Êä³öÄ£Ä⣩       

    static int get_cnt();

private:
    static int 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();
}
  • 运行截图

屏幕截图 2026-11-19 191630

  • 问题
    因为total_cnt是static的静态成员,属于整个类,不属于某一个实例对象。

任务四

选择方案一

  • 源代码
    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 &a, const Fraction &b);
    friend Fraction sub(const Fraction &a, const Fraction &b);
    friend Fraction mul(const Fraction &a, const Fraction &b);
    friend Fraction div(const Fraction &a, const Fraction &b);

private:
    int up;
    int down;
    void reduce(); 
};

Fraction.cpp
点击查看代码
#include "Fraction.h"
#include <stdexcept>
#include <iostream>
#include <algorithm>

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

static int gcd(int a,int b){
    a=std::abs(a);
    b=std::abs(b);
    while(b){
        int t=a%b;
        a=b;
        b=t;
    }
    return a;
}

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

Fraction::Fraction(int up0):up(up0), down(1){
    reduce();
}
Fraction::Fraction(int up0, int down0):up{up0}, down{down0}{
    if(down0 == 0) throw std::invalid_argument("Fraction: 分母不能为0");
    reduce();
}
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 &a, const Fraction &b){
    int nu = a.up * b.down + b.up * a.down;
    int nd = a.down * b.down;
    return Fraction(nu, nd);
}

Fraction sub(const Fraction &a, const Fraction &b){
    int nu = a.up * b.down - b.up * a.down;
    int nd = a.down * b.down;
    return Fraction(nu, nd);
}

Fraction mul(const Fraction &a, const Fraction &b){
    int nu = a.up * b.up;
    int nd = a.down * b.down;
    return Fraction(nu, nd);
}

Fraction div(const Fraction &a, const Fraction &b){
    if(b.up == 0){
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    int nu = a.up * b.down;
    int nd = a.down * b.up;
    return Fraction(nu, nd);
}




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();
}
  • 运行截图

屏幕截图 2026-11-19 193145

  • 问题
    选择方案一的理由是四则运算、输出函数需要频繁读取分子、分母私有成员,使用友元可以直接访问私有成员,不需要反复调用 get_up、get_down 接口,这样代码更加简洁。
posted @ 2026-11-19 19:37  n的五次方  阅读(3)  评论(0)    收藏  举报