实验二

实验任务一

源码

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

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

测试截图

image

问题1

第7行,是一个普通构造函数,用来初始化一个对象
第8行,是复制构造函数,用一个对象初始化另一个对象
第9行,是一个移动构造函数,用一个临时对象来初始化一个对象
第10行,是一个析构函数。当对象生命周期结束会调用来进行清理
t1,t2是普通构造函数,t3是复制构造函数,t4是移动构造

问题2

截图

image

原因分析

报错信息是生成项目.exe失败,分析得到编译虽然完成但是链接器报重复定义,这和前面四行中出现的两次first defined here对应。

问题3

从开始定义一直到test结束,另外不能实现访问,会在编译期直接拒绝,这体现了类的封装。

问题4

程序崩溃了image
不会被销毁,因为异常始终未被捕获,t1,t2的析构函数没有被调用,current_cnt 也没有减回去。

实验任务2

源码

(complex.h)

#pragma once

#include <string>

class Complex {
public:
    static const std::string doc;      // class description (const, public)

    Complex(double re = 0.0, double im = 0.0);   // NOTE: no explicit!
    Complex(const Complex &c);                   // copy ctor

    double real() const;               // must be const
    double imag() const;               // must be const

    void add(const Complex &c);        // c1.add(c2)  ->  c1 += c2

    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 re_, im_;
};

(complex.cpp)

#include "Complex.h"

#include <cmath>
#include <iostream>
const std::string Complex::doc{"a simplified complex class"};

Complex::Complex(double re, double im) : re_(re), im_(im) {
}

Complex::Complex(const Complex &c) : re_(c.re_), im_(c.im_) {
}

double Complex::real() const {
    return re_;
}
double Complex::imag() const {
    return im_;
}

void Complex::add(const Complex &c) {
	re_ += c.re_;
    im_ += c.im_;
}

void output(const Complex &c) {
	std::cout << c.re_;
    if (c.im_ >= 0)
        std::cout << " + " << c.im_ << "i";
    else
        std::cout << " - " << -c.im_ << "i";
}

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

Complex add(const Complex &a, const Complex &b) {
    return Complex(a.re_ + b.re_, a.im_ + b.im_);
}

bool is_equal(const Complex &a, const Complex &b) {
    const double eps = 1e-9;
    return std::fabs(a.re_ - b.re_) < eps
        && std::fabs(a.im_ - b.im_) < eps;
}

bool is_not_equal(const Complex &a, const Complex &b) {
    return !is_equal(a, b);
}

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

问题1

1,real()/imag() 必须加 const;不加会报 passing 'const Complex' as 'this' argument ... discards qualifiers。
2,c6.add(c2); 编译不通过,const 对象不能调非 const 成员函数,体现 const 保护机制。

问题2

标准库模板更加简洁,函数和运算符一一对应,是把函数包装成运算符。

问题3

1,不是必须的:不用friend的话,可以调用real,imag函数在普通非成员情况下实现同样功能。
2,没有image
链接:https://zh.cppreference.net/cpp/numeric/complex/abs.html
3,当外部函数必须作为一个整体对象来读写内部数据、又不该成为成员时一般用friend,来减少接口暴露。

实验任务3

源码

PlayerControl.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(), ::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;
}

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

问题

是因为total_cnt是static成员,const函数可以对静态成员变量进行修改。

实验任务4

源码

Fraction.cpp

#include "Fraction.h"

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

// 只在本文件内使用的辅助函数:求最大公约数
namespace {
    int gcd(int a, int b) {
        if (a < 0) a = -a;
        if (b < 0) b = -b;
        while (b != 0) {
            int t = a % b;
            a = b;
            b = t;
        }
        return a;
    }
}

// 静态常量成员:类内声明,类外定义一次
const std::string Fraction::doc{
    "Fraction类 v 0.01版.\n"
    "目前仅支持分数对象的构造、输出、加/减/乘/除运算."
};

Fraction::Fraction(int up, int down) : up_(up), down_(down) {
    if (down_ == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }

    // 负号统一放到分子上,保证分母为正
    if (down_ < 0) {
        up_ = -up_;
        down_ = -down_;
    }

    // 约分
    int g = gcd(up_, down_);
    if (g > 1) {
        up_ /= g;
        down_ /= g;
    }
}

Fraction::Fraction(const Fraction &f) : up_(f.up_), down_(f.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) {
    return Fraction(a.up_ * b.down_ + b.up_ * a.down_,
                    a.down_ * b.down_);
}

Fraction sub(const Fraction &a, const Fraction &b) {
    return Fraction(a.up_ * b.down_ - b.up_ * a.down_,
                    a.down_ * b.down_);
}

Fraction mul(const Fraction &a, const Fraction &b) {
    return Fraction(a.up_ * b.up_, a.down_ * b.down_);
}

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

Fraction.h

#pragma once

#include <string>

class Fraction {
public:
    static const std::string doc;        // 类的说明信息,常量、公有

    Fraction(int up = 0, int down = 1);  // 分母为 0 时抛出异常
    Fraction(const Fraction &f);         // 复制构造函数

    int get_up() const;                  // 取分子
    int get_down() const;                // 取分母

    Fraction negative() const;           // 返回相反数,不改变自身

    friend void     output(const Fraction &f);   // 输出,形如 -3/4
    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_, down_;                      // 分子、分母(分母为正)
};

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

选方案1。友元方案能原样通过测试、不必改动测试代码,并且output、add等函数需要对up_、down_做整体运算,友元比额外暴露一堆get接口更简洁,也保持了封装。

posted @ 2026-11-19 20:22  爱梦游的天姥  阅读(5)  评论(0)    收藏  举报