实验2

实验任务1

  • 源代码

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

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

  • 问题回答

实验1问题1

回答:
T(int x=0, int y=0)普通构造用两个 int 初始化 m1、m2定义新对象时给 0~2 个 int 实参,T t1; 走默认值`
T(const T&) 复制构造用另一个同类型左值对象初始化新对象,逐成员拷贝T t3(t2);函数按值传参、返回对象
T(T&&) 移动构造用**右值 / 将亡值初始化,语义上是把源对象的资源 "搬" 过来T t4(std::move(t2));、接收临时对象
~T() 析构对象消亡前清理,这里做 --current_cnt离开作用域({} 结束)、delete、临时对象用完;按构造逆序执行

1–t4 分别触发:t1 → 普通构造;t2 → 普通构造;t3 → 复制构造;t4 → 移动构造。

实验1问题2

回答:不能。

  • 报错截图

1

原因:那三行是定义(分配存储、给初值),不是声明。头文件被 t.cpp 和 task1.cpp各 include 一次,两个目标文件里就各有了一份同名定义。这样就会形成重复定义的问题。

实验1问题3

回答:
作用域:都是 test() 里那个 {} 块内的局部变量,名字从声明处可见到 }为止。
生命期:从构造完成开始(自动存储期、栈上),到离开 } 结束,逆序析构。证据就是输出:块内 current count: 4,出块后 0。

能否访问t1 m1访问私有成员:不能
原因:因为 test() 是普通函数,既不是成员函数也不是友元。这体现的是封装(访问控制 / 信息隐藏):private 只向本类成员函数和 friend 开放,外部只能通过 public 接口使用对象。

实验1问题4

回答:
hrow 表达式 做三件事:① 用括号里的值构造一个异常对象(这里是 std::runtime_error,消息是 "T: maximum object count exceeded");② 立即结束当前函数的正常流程,把异常抛给调用者;③ 沿调用栈逐层查找匹配的 catch,找到就跳进去执行,跳之前沿途的局部对象会被析构(栈展开);一层都没找到就调用 std::terminate,程序 abort,于是打印这里用它做 “对象总数上限” 保护:超过 999 就不允许再构造。
如果改成2,实验能正常结束但只构造了两个,如图:

实验一问题4运行截图

而创建的对象并不会被正常销毁,因为34都是异常

实验任务2

  • 源代码
点击查看代码

  • 运行测试截图

  • 问题回答

实验二问题1
(1)必须加的关键字:const,加在成员函数参数表后面。如果不加则会出现:

实验2运行错误截图

(2)c6.add(c2)编译不能通过。原因:add() 要执行 re += ...; im += ...;,它必须修改对象,所以只能是**非 const 成员函数;而 c6 是 const 对象,只能调用 const 成员函数,c6.add()这个组合在编译期就被判死刑。

体现的保护机制:const 成员函数机制(常量正确性 const-correctness—— 用 const在类型系统里把 "只读对象" 和 "可写对象" 区分开,让 "试图修改 const 对象" 在编译阶段就被拦住,而不是运行时出错。它保护的是"对象初始化后其状态不会被函数偷偷改掉

实验2问题2

回答:哪种更简洁:标准库明显更简洁。

理由:① 运算符重载后写法与数学一致,c1 += c2、c4 = c2 + c3、c1 == c2 一眼就懂,不用记 add、is_equal、is_not_equal 这些函数名;② 模板化,complex、complex 一份代码通用;③ 能和内置类型混算(c1 + 2.5、c1 == 0),自定义版必须写 add(c2, Complex(2.5));④ 流输出 / 输入直接 << >>,不用 output()。

函数与运算符是否存在内在关联:是,运算符本质就是函数。

实验2问题3
(1)不是必须的,不用friend一样能跑。理由:friend 只在一种情况下变成 "必须":你既不想提供 real()/imag() 这类接口,又要让外部函数直接读写私有成员。此时只能靠 friend。
而且 friend 关系是不继承、不传递、是单向的,会将外部函数直接包装为私有。
(2)不是。std::complex 没有把 abs 设为友元
中文镜像(实测可开)

  • 类主页:https://cppreference.cn/w/cpp/numeric/complex
  • 头文件页:https://cppreference.cn/w/cpp/header/complex
    (3)仅当外部函数必须直接访问私有成员、又不便新增 public 接口时才用:典型是 operator<</operator>> 流运算符、两类之间的对称运算符(如 Matrix * Vector)、以及紧耦合的内部工具。能用公开接口就别用,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;
    for (std::size_t i = 0; i < s.size(); ++i) {
        if (s[i] >= 'A' && s[i] <= 'Z')    
            s[i] = s[i] - 'A' + 'a';        
    }

    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

点击查看代码

+ 运行测试截图

实验3运行截图

  • 问题回答

问题1
接口 void execute(ControlType cmd) const; 是const成员函数,为什么在其内部实现允许代码++total_cnt ?
回答:因为 total_cnt 是静态数据成员(static),它属于整个类而不属于任何对象:全类只有一份,存在静态存储区,没有 this 指针。而 const 成员函数承诺的只是 “不修改本对象的非静态数据成员”,在函数内部this 被看成 const PlayerControl,凡是经 this 访问的普通成员都被加上只读限制;访问静态成员根本不需要经过 this(编译期PlayerControl::total_cnt 直接解析),所以不受这条只读限制约束

实验任务4

  • 源代码

Fraction.h

点击查看代码
#include <iostream>
#include <stdexcept>

class Fraction {
public:
    static const char* doc;

    Fraction(int up = 0, int down = 1) {
        if (down == 0)
            throw std::invalid_argument("Fraction: 分母不能为0");
        if (down < 0) { up = -up; down = -down; }     
        int g = gcd_of(abs_of(up), down);           
        this->up = up / g;
        this->down = down / g;
    }

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

    int get_up() const { return up; }
    int get_down() const { return down; }

private:
    int up;
    int down;
    static int abs_of(int x) { return x < 0 ? -x : x; }
    static int gcd_of(int a, int b) {             
        while (b != 0) { int t = a % b; a = b; b = t; }
        return a;
    }
};

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

void output(const Fraction& f) {
    if (f.get_down() == 1) std::cout << f.get_up();  
    else 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) {
    if (b.get_up() == 0) throw std::invalid_argument("Fraction: 分母不能为0");
    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运行截图

  • 问题回答

问题1
分数运算( output/add/sub/mul/div ),你选择的是哪种设计方案?你的决策理由?
方案1:分数类 + 友元函数
方案2:分数类 + 命名空间自由函数
回答:我选择方案 2。理由:
(1) 不需要 friend 也能算类的数据成员 up/down 是 private,但同时提供了 public 的 get_up()/get_down() 只读接口,运算函数靠这两个接口就能取到分子分母,没必要再开一个 “直接摸私有数据” 的后门。
(2)friend 的代价大于收益。友元会把类的内部表示暴露给外部函数,每增加一个运算就要回类里再补一条 friend 声明,类的定义被绑死;而且 friend 不可继承、不可传递,谁有权限动内部数据会变得难查

posted @ 2026-11-18 22:29  空-zzz  阅读(2)  评论(0)    收藏  举报