实验二

实验任务一

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

  

#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类对象数目
};

  

#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-17 141915

问题一:

1.T(int x=0,int y=0)是普通构造函数:创建对象时初始化成员。调用时机:定义对象,没有提供已有对象拷贝时调用。t1,t2调用普通构造。

2. T(const T &t)拷贝构造:用已有对象复制生成新对象,用旧对象初始化新对象,值传递传参,函数返回对象时调用。t3(t2)调用拷贝构造。

3.T(T &&t)移动构造:接管临时 对象资源,避免拷贝。t4(std::move(t2))触发移动构造

4.~T()析构函数:对象销毁前释放资源。t1/t2/t3/t4结束时全部调用析构。

问题二:

不能正确编译。

error: cannot define static data member inside class。

类的静态数据成员,类内只做声明,必须在类的外部全局域进行定义初始化,把这些写进头文件类末尾,变成类内部定义。

问题三:

作用域限于大括号内,生命周期从定义语句开始,到右大括号结束,出大括号对象销毁,析构执行。

不能访问,体现了封装特性。

问题四:

屏幕截图 2026-11-17 145542

throw:抛出异常对象,中断正常执行流程,交给异常捕获处理;本代码没有try-catch。

程序直接崩溃终止,没有正常结束。已经创建的 t1、t2 会正常销毁。

实验任务二:

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

  

#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) {
    Complex res;
    res.real_ = c1.real_ + c2.real_;
    res.imag_ = c1.imag_ + c2.imag_;
    return res;
}

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

  

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

  运行截图

屏幕截图 2026-11-17 150449

问题一:

加上const修饰成员函数

不加 const 时报错:不能在 const 对象上调用非 const 成员函数。

问题二:

std::complex<T>标准库模板使用形式更简洁。

存在内在关联:编译器将运算符表达式转换为对应函数调用。

问题三:

元友不是必须的

普通非成员函数实现思路:不访问私有成员,调用类提供的real()、imag()的 public 接口获取实部虚部,完成计算。不需要 friend。

std::complex 的 abs不是友元函数;是普通非成员模板函数。

friend 使用场景:普通成员接口无法满足,需要外部函数高效直接访问私有成员;需要实现二元运算符,左操作数不是本类对象;性能敏感场景。尽量少用,友元会破坏封装,优先使用 public 接口。

实验任务三

 

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

  

#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(),
        [](unsigned char ch){ return std::tolower(ch); });

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

  

#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-17 160031

问题:

otal_cnt是static 静态成员,属于整个类,不属于某一个实例对象。const成员函数限制只针对实例对象普通成员,静态成员不受这个 const 限制,所以可以修改total_cnt。

实验任务四

#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(); //内部工具函数,约分,保证分母>0
    static int gcd(int a,int b);
};

  

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

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

int Fraction::gcd(int a, int b) {
    a = std::abs(a);
    b = std::abs(b);
    while(b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

void Fraction::reduce() {
    int g = gcd(up, down);
    up /= g;
    down /= g;
    if(down < 0) {
        up = -up;
        down = -down;
    }
}

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

Fraction::Fraction(int up0, int down0): up{up0}, down{down0} {
    if(down == 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 de = a.down * b.down;
    return Fraction(nu, de);
}

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

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

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

  

#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-17 161443

问题:

选择:方案 1:分数类 + 友元函数

运算函数需要直接访问私有分子up分母down;使用友元,不用额外写大量 public getter 调用,代码简洁

实验总结:我熟悉多文件分离编译.h头文件声明,.cpp实现文件,掌握普通构造、拷贝构造、移动构造、析构调用时机

posted @ 2026-11-18 10:11  tyyyyyxy  阅读(0)  评论(0)    收藏  举报