实验2

实验结论

1.实验任务1

源码

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

运行截图

image
image

问题回答

问题1:t.h中,line7-10给出了各种构造函数、析构函数。用文字简洁说明它们各自的功能、调用时机。结合t1
t4,说明它们分别触发了哪个构造函数

普通构造函数T(int x, int y):用于创建新对象,并用传入的参数初始化对象的m1、m2。如果创建对象时没有传入参数,就使用默认参数0。对象定义时调用
复制构造函数T(const T& t):根据一个已经存在的同类对象创建新对象,并复制它的数据成员。用一个已有对象初始化新对象时调用
移动构造函数T(T&& t):使用右值引用接收可移动的对象,并据此构造新对象,通常用来临时对象或通过std::move转换得到的右值
析构函数~T():对象生命周期结束时调用,用于完成对象销毁前的清理工作。本程序中还会将当前对象数量减一

t1没有传入参数,调用带默认参数的普通构造函数;t2(3, 4)调用普通构造函数;t3(t2)调用复制构造函数;t4(std::move(t2))调用移动构造函数

问题2:t.cpp中,line8-10,剪切到t.h的末尾,重新编译,程序能否正确编译。
如不能,以截图形式给出报错信息,分析原因。
image
image

不能。line8-10是静态成员的定义,放到头文件,由于t.cpp和task1.cpp都包含了t.h,两个源文件在编译后都会产生同一组静态成员定义,最终可能出现重复定义

问题3:类T的测试模块
test 中,说明对象 t1-t4 的作用域和生命期。并思考:在这个作用域内,能否通过 t1 访
问其私有成员 m1、m2?这体现了类的什么特性?

t1~t4都定义在test()函数内部的{}中,因此它们的作用域仅限于这个内部。生命周期从各自构造完成时开始,到内部结束时结束;销毁顺序与构造顺序相反
不能。m1、m2被声明在private部分,类外代码不能直接访问
体现了类的封装和数据隐藏特性。类的成员函数以及被声明为友元的函数可以在规定范围内访问这些私有数据

问题4:t.cpp中包含了头文件

include ,构造函数中均使用了以下代码。使用搜索引擎/AI查询

throw 功能。
把t.cpp中T::MAX_CNT值改成2,重新编译、运行程序。观察输出,程序是正常结束还是崩溃了?给出截
图运行结果。
如果崩溃了,已经创建的对象(如t1),会被正常销毁吗?给出答案,并说明理由。

throw用于抛出异常。当程序遇到异常情况时,可以通过throw抛出一个异常对象,程序会停止当前正常执行流程,并寻找能够处理该异常的catch语句。如果异常没有被捕获,程序最终会调用std::terminate()结束运行。对于未捕获的异常,在调用std::terminate()前是否进行栈展开由具体实现决定;如果发生栈展开,已经构造完成的局部对象会调用析构函数。

image
不会。输出里没有出现T destructor called,析构函数是在对象"正常离开作用域"时自动调用的,也就是程序走到}的时候,但程序是被terminate直接强制结束的,没有走到test()里内层花括号的},t1、t2的析构函数都没机会执行,局部对象被丢下了

2.实验任务2

源码

Complex.h

#pragma once

#include <string>

class Complex {
public:
    static const std::string doc;

    Complex(double real = 0.0, double imag = 0.0);

    double real() const;
    double imag() const;
    void add(const Complex& other);

    friend void output(const Complex& value);
    friend double abs(const Complex& value);
    friend Complex add(const Complex& lhs, const Complex& rhs);
    friend bool is_equal(const Complex& lhs, const Complex& rhs);
    friend bool is_not_equal(const Complex& lhs, const Complex& rhs);

private:
    double real_;
    double imag_;
};

Complex.cpp

#include "Complex.h"

#include <cmath>
#include <iostream>

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

Complex::Complex(double real, double imag) : real_(real), imag_(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& value) {
    std::cout << value.real_;
    if (value.imag_ >= 0) {
        std::cout << " + " << value.imag_ << "i";
    } else {
        std::cout << " - " << std::abs(value.imag_) << "i";
    }
}

double abs(const Complex& value) {
    return std::hypot(value.real_, value.imag_);
}

Complex add(const Complex& lhs, const Complex& rhs) {
    return Complex(lhs.real_ + rhs.real_, lhs.imag_ + rhs.imag_);
}

bool is_equal(const Complex& lhs, const Complex& rhs) {
    return lhs.real_ == rhs.real_ && lhs.imag_ == rhs.imag_;
}

bool is_not_equal(const Complex& lhs, const Complex& rhs) {
    return !is_equal(lhs, rhs);
}

task2.cpp

#include <iomanip>
#include <iostream>
#include <complex>

#include "Complex.h"

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

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
image

问题回答

问题1:
在测试代码中,c6是cons对象。
① 为了让 c6.real() 和 c6.imag()能编译通过,在设计 Complex 类的成员函数时,必须加上什么关键字?
如果不加,编译器会报什么错?(请简述或截图报错信息)。
② 作为const对象,c6在初始化后允许再被修改。在测试代码中添加执行 c6.add(c2);,能编译通过吗?为什
么?这体现了类的什么保护机制?

  1. 需要在real()和imag()的函数声明及定义后面加上const,将它们声明为常成员函数

  2. 不能。add()会修改调用对象的实部和虚部,所以它不能声明为常成员函数;而c6是const Complex对象,不能调用可能修改自身状态的非const成员函数
    体现了C++通过const对象和常成员函数实现的数据保护机制

问题2:
比较自定义类Complex和标准库模板类complex的用法,在使用形式上,哪种更简洁?据此推断函数和运算是
否存在内在关联呢?

标准库std::complex更简洁。例如复数相加可以直接写成c4 = c2 + c3,比较可以写成c1 == c2,输出可以直接使用cout << c1
关联是运算符可以通过运算符重载与类的操作建立联系

问题3:
① 本练习中,output、abs、add(非成员版本)等被设为Complex的友元。这是必须的吗?如果将其声明
为普通非成员函数(不用friend),能否实现相同的功能?简述思路。
② 标准库 std::complex 是否把 abs 设为友元?(查阅 cppreference后回答,并提供页面具体链接地址)
③ 工业场景中,什么时候才考虑使用 friend?和AI讨论后,简洁概括你的思考和结论。(限150字内)

  1. 不是。如果类提供了real()、imag()等公有接口,普通非成员函数就可以通过这些接口获取数据,再完成输出、求模和复数相加等操作。友元函数的优点是可以直接访问私有成员,写起来比较方便;缺点是会扩大类内部数据的访问范围,增加类与外部函数之间的联系

  2. 不是。cppreference将其列为定义在中的非成员函数模板,函数接收const complex&并返回复数的模。它可以通过std::complex提供的公有接口取得实部和虚部,不需要友元权限。参考链接:cppreference:std::abs(std::complex)

  3. 只有当某个外部函数确实需要访问类的私有成员,而且通过公有接口实现不够合适时,才考虑使用friend。例如某些需要同时访问两个对象内部数据的运算符重载。友元应该按需使用,不能为了少写几个访问函数就随意扩大数据访问权限


3.实验任务3

源码

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 <cctype>
#include <iostream>

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

ControlType PlayerControl::parse(const std::string& control_str) {
    std::string command = control_str;
    std::transform(command.begin(), command.end(), command.begin(), [](unsigned char ch) {
        return static_cast<char>(std::tolower(ch));
    });

    if (command == "play") return ControlType::Play;
    if (command == "pause") return ControlType::Pause;
    if (command == "next") return ControlType::Next;
    if (command == "prev") return ControlType::Prev;
    if (command == "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

问题回答

接口void execute(ControlType cmd) const;是const成员函数,为什么在其内部实现允许代码
++total_cnt?

total_cnt是类的静态数据成员,它属于整个类,而不是某一个具体对象。常成员函数的限制主要是不允许通过当前对象修改普通的非静态数据成员,但并不禁止修改静态数据成员


4.实验任务4

源码

方案2:分数类+命名空间自由函数

Fraction.h

#pragma once

#include <string>

class Fraction {
public:
    static const std::string doc;

    Fraction(int up0 = 0, int down0 = 1);

    int get_up() const;
    int get_down() const;
    Fraction negative() const;

private:
    int up;
    int down;
};

namespace frac {
    void output(const Fraction& value);
    Fraction add(const Fraction& lhs, const Fraction& rhs);
    Fraction sub(const Fraction& lhs, const Fraction& rhs);
    Fraction mul(const Fraction& lhs, const Fraction& rhs);
    Fraction div(const Fraction& lhs, const Fraction& rhs);
}

Fraction.cpp

#include "Fraction.h"

#include <iostream>
#include <stdexcept>

namespace {
    int gcd_value(int a, int b) {
        if (a < 0) a = -a;
        if (b < 0) b = -b;
        while (b != 0) {
            int remainder = a % b;
            a = b;
            b = remainder;
        }
        return a == 0 ? 1 : a;
    }
}

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

Fraction::Fraction(int up0, int down0) {
    if (down0 == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }

    if (down0 < 0) {
        up0 = -up0;
        down0 = -down0;
    }

    int divisor = gcd_value(up0, down0);
    up = up0 / divisor;
    down = down0 / divisor;
}

int Fraction::get_up() const {
    return up;
}

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

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

void frac::output(const Fraction& value) {
    int numerator = value.get_up();
    int denominator = value.get_down();

    if (numerator == 0 || denominator == 1) {
        std::cout << numerator;
    } else {
        std::cout << numerator << "/" << denominator;
    }
}

Fraction frac::add(const Fraction& lhs, const Fraction& rhs) {
    int numerator = lhs.get_up() * rhs.get_down() + rhs.get_up() * lhs.get_down();
    int denominator = lhs.get_down() * rhs.get_down();
    return Fraction(numerator, denominator);
}

Fraction frac::sub(const Fraction& lhs, const Fraction& rhs) {
    int numerator = lhs.get_up() * rhs.get_down() - rhs.get_up() * lhs.get_down();
    int denominator = lhs.get_down() * rhs.get_down();
    return Fraction(numerator, denominator);
}

Fraction frac::mul(const Fraction& lhs, const Fraction& rhs) {
    return Fraction(lhs.get_up() * rhs.get_up(), lhs.get_down() * rhs.get_down());
}

Fraction frac::div(const Fraction& lhs, const Fraction& rhs) {
    if (rhs.get_up() == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    return Fraction(lhs.get_up() * rhs.get_down(), lhs.get_down() * rhs.get_up());
}

task4.cpp

#include <iostream>
#include <stdexcept>

#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 = "; frac::output(f1); cout << endl;
    cout << "f2 = "; frac::output(f2); cout << endl;
    cout << "f3 = "; frac::output(f3); cout << endl;
    cout << "f4 = "; frac::output(f4); cout << endl;

    const Fraction f5(f4.negative());
    cout << "f5 = "; frac::output(f5); cout << endl;
    cout << "f5.get_up() = " << f5.get_up()
         << ", f5.get_down() = " << f5.get_down() << endl;

    cout << "f1 + f2 = "; frac::output(frac::add(f1, f2)); cout << endl;
    cout << "f1 - f2 = "; frac::output(frac::sub(f1, f2)); cout << endl;
    cout << "f1 * f2 = "; frac::output(frac::mul(f1, f2)); cout << endl;
    cout << "f1 / f2 = "; frac::output(frac::div(f1, f2)); cout << endl;
    cout << "f4 + f5 = "; frac::output(frac::add(f4, f5)); cout << endl;
}

void test2() {
    using std::cout;
    using std::endl;

    Fraction f6(42, 55), f7(0, 3);
    cout << "f6 = "; frac::output(f6); cout << endl;
    cout << "f7 = "; frac::output(f7); cout << endl;

    try {
        cout << "f6 / f7 = "; frac::output(frac::div(f6, f7)); cout << endl;
    }
    catch (const std::invalid_argument& e) {
        cout << endl << "捕获到异常: " << e.what() << endl;
    }
}

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

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

运行截图

image

问题回答

分数运算(
output/add/sub/mul/div ),你选择的是哪种设计方案?你的决策理由?
方案1:分数类 + 友元函数
方案2:分数类 + 命名空间自由函数

方案2。Fraction类主要负责保存分子和分母,并在构造时统一处理分母符号和约分;加减乘除以及输出操作并不依赖某一个对象,而是对两个分数进行计算后返回一个新分数,因此使用普通自由函数比较合适
同时,类已经提供了get_up()和get_down()两个公有接口,命名空间中的函数可以通过它们获取计算所需的数据,不必直接访问私有成员,也不需要使用friend,代码的职责比较清楚。为了避免函数名与其他库函数混淆,将这些自由函数统一放在frac命名空间中


posted @ 2026-11-19 23:21  BONKbonk  阅读(2)  评论(0)    收藏  举报