实验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();          // 显示当前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类对象数目
};

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

2.图片

tak1

3.回答问题

问题1

普通构造函数 T(int x = 0, int y = 0):在创建对象并给它赋初值的时候调用。t1 和 t2触发。
复制/拷贝构造函数 T(const T &t):用已经存在的对象去初始化一个新对象时调用。t3(t2) 触发。
移动构造函数 T(T &&t):用 std::move() 把一个对象的资源“转移”给新对象时调用。t4(std::move(t2)) 触发。
析构函数 ~T():对象生命走到尽头时自动调用。在 test() 的大括号结束时,t4, t3, t2, t1 会依次调用析构。

问题2

图片

问题2
如果在头文件里写 int T::current_cnt = 0;,因为头文件会被多个源文件包含,这就相当于在多个文件里都定义了一次这个全局变量。编译链接的时候,编译器会发现同一个变量被定义了多次,直接报“多重定义 (multiple definition)”的链接错误。

问题3

1.这四个对象的生命周期都只在 test() 函数内部的那对 {} 之间。出了这个 {},对象就被销毁了。
2.不能。 m1 和 m2 在类 T 里是 private(私有)的。
3.体现了类的封装性。

问题4

throw 就是抛出异常的意思。当程序遇到某种“不应该发生”或者“无法处理”的情况时,用 throw 扔出一个错误信号。

图片

问题4
程序会直接崩溃
会被正常销毁,当异常被抛出时,程序会从抛出点开始,沿着函数调用栈往回退,并且在退出的过程中,会自动调用局部对象的析构函数。所以在程序崩溃退出 test() 作用域之前,t1 和 t2 是会被正常执行析构函数的。

实验任务2

1.代码

Complex.h

#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
#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);

private:
    double real_val;
    double imag_val;

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

#endif

Complex.cpp

#include "Complex.h"
#include <cmath>
using namespace std;

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

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

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

void output(const Complex& c)
{
    cout << c.real_val << " + " << c.imag_val << "i";
}
double abs(const Complex& c)
{
    return sqrt(c.real_val * c.real_val + c.imag_val * c.imag_val);
}
Complex add(const Complex& a, const Complex& b)
{
    return Complex(a.real_val + b.real_val, a.imag_val + b.imag_val);
}
bool is_equal(const Complex& a, const Complex& b)
{
    return a.real_val == b.real_val && a.imag_val == b.imag_val;
}
bool is_not_equal(const Complex& a, const Complex& b)
{
    return !is_equal(a, b);
}

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

2.图片

实验2

3.问题

问题1

加const代表这个成员函数不会修改对象里的数据,是只读函数。不加的话,const对象不能调用它,会编译报错。add函数会修改对象内部的值,而c6是const常量对象,不允许修改,所以无法调用add。

问题2

相同点:都封装实部、虚部,用来表示复数,支持复数相加、求模、判断相等。
不同点:标准库直接重载了+、+=、==这些运算符,写法简洁;我们写的版本要用add、is_equal这类单独函数实现功能。

问题3

不一定非要友元。如果类提供public的real()、imag()读取接口,函数就可以通过这两个接口拿到实部虚部,不用friend。友元只是方便直接访问私有成员,但会破坏封装性。

实验报告3

1.代码

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

PlayControl.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;
    //全部转小写
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
    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.h

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

问题3

const成员函数的限制是不能修改本对象的非静态成员变量;而total_cnt是static静态成员,不属于某一个对象,属于整个类,不受这个const的约束,所以可以修改。

实验报告4

1.代码

Fraction.h

#pragma once
#include <string>

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

        Fraction(int up0 = 0);
        Fraction(int up0, int down0);
        Fraction(const Fraction& other);

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

    private:
        int up;
        int down;
        void reduce();
        static int gcd(int a, int b);
    };

    void output(const Fraction& f);
    Fraction add(const Fraction& a, const Fraction& b);
    Fraction sub(const Fraction& a, const Fraction& b);
    Fraction mul(const Fraction& a, const Fraction& b);
    Fraction div(const Fraction& a, const Fraction& b);
}
using frac::Fraction;
using frac::output;
using frac::add;
using frac::sub;
using frac::mul;
using frac::div;

Fraction.cpp

#include "Fraction.h"
#include <stdexcept>
#include <iostream>
#include <algorithm>

namespace frac {
const std::string Fraction::doc =
R"(Fraction类 v 0.01版.
目前仅支持分数对象的构造、输出、加/减/乘/除运算.)";
int Fraction::gcd(int a, int b)
{
    a = abs(a);
    b = abs(b);
    while(b)
    {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

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

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

Fraction::Fraction(int up0, int down0)
{
    up = up0;
    down = down0;
    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)
{
    std::cout << f.get_up() << "/" << f.get_down();
}
Fraction add(const Fraction& a, const Fraction& b)
{
    return Fraction(a.get_up()*b.get_down() + b.get_up()*a.get_down(), a.get_down()*b.get_down());
}
Fraction sub(const Fraction& a, const Fraction& b)
{
    return Fraction(a.get_up()*b.get_down() - b.get_up()*a.get_down(), a.get_down()*b.get_down());
}
Fraction mul(const Fraction& a, const Fraction& b)
{
    return Fraction(a.get_up()*b.get_up(), a.get_down()*b.get_down());
}
Fraction div(const Fraction& a, const Fraction& b)
{
    return Fraction(a.get_up()*b.get_down(), a.get_down()*b.get_up());
}

} 

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

图片

4

问题

我选择分数类搭配命名空间自由函数的方案。四则运算、输出属于分数相关操作,但不属于对象自身行为,使用命名空间自由函数职责清晰,不破坏封装;同时命名空间可以隔离函数名,避免命名冲突,后续新增运算时也无需修改类的内部代码,扩展性更好。

posted @ 2026-11-19 12:49  bqcz  阅读(4)  评论(0)    收藏  举报