作业2

实验任务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();
}

运行截图

1

 

 

问题 1

  1. 普通构造函数T(int x = 0, int y = 0):初始化对象成员,支持默认参数;直接定义对象时调用。
  2. 拷贝构造函数T(const T &t):用已有对象拷贝生成新对象;使用已有对象初始化新对象时调用。
  3. 移动构造函数T(T &&t):接收右值,构造新对象;std::move转换左值为右值初始化对象时调用。
  4. 析构函数~T():对象销毁时清理、对象计数减一;对象离开作用域时调用。 对象触发: t1、t2:普通构造函数;t3:拷贝构造函数;t4:移动构造函数。

问题 2

不能正常编译。 原因:静态成员doc、current_cnt、MAX_CNT的类外定义如果放到头文件,头文件会被多个源文件包含,造成重复定义,链接阶段报错multiple definition。静态成员的类外定义只能放在.cpp文件。

2

 

 

问题 3

t1、t2、t3、t4 都在 test 内的内层{}块作用域中,进入大括号时构造,离开大括号时生命周期结束、对象销毁。 不能直接通过t1访问私有成员m1,m2;体现了类的封装特性,隐藏内部数据,仅通过公有接口、友元访问私有成员。

问题 4

将T::MAX_CNT改为 2 后,程序抛出异常并终止,不会正常跑完。 已经成功创建的t1、t2会正常销毁。 理由:C++ 异常的栈展开机制,抛出异常时,该作用域内构造完成的局部对象会自动调用析构;t3 在构造函数内、计数增加前就抛出异常,构造未完成,不会生成对象,也就不会析构。

3

实验任务2

源代码

Complex.h

#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& 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 real_;
    double imag_;
};

Complex.cpp

#include "Complex.h"
#include <iostream>
#include <cmath>

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

// 无参构造:0+0i
Complex::Complex() : real_(0), imag_(0) {}
// 单参数构造:r+0i
Complex::Complex(double r) : real_(r), imag_(0) {}
// 双参数构造:r + i*i
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_;
}

// 成员add:this += other
void Complex::add(const Complex& other) {
    real_ += other.real_;
    imag_ += other.imag_;
}

// 友元 output,a+bi格式
void output(const Complex& c) {
    std::cout << c.real_ << " " << c.imag_ << "i";
}
// 友元 abs:求模
double abs(const Complex& c) {
    return sqrt(c.real_ * c.real_ + c.imag_ * c.imag_);
}
// 友元 add:返回 a+b 的新复数
Complex add(const Complex& a, const Complex& b) {
    return Complex(a.real_ + b.real_, a.imag_ + b.imag_);
}
// 判断相等
bool is_equal(const Complex& a, const Complex& b) {
    return (a.real_ == b.real_) && (a.imag_ == b.imag_);
}
// 判断不等
bool is_not_equal(const Complex& a, const Complex& b) {
    return !is_equal(a, b);
}

  

task2

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

运行截图

4

5

问题 1

① 必须加 const(放在成员函数末尾)。 不加报错:passing 'const Complex' as 'this' argument discards qualifiers,含义:不能用 const 对象调用非 const 成员函数。

② 不能编译通过。 理由:add()是普通非 const 成员函数,会修改对象数据;const对象的this是const Complex*,不允许调用会修改自身的成员函数。 体现const 常量保护机制,保证 const 对象初始化后数据不可修改。

问题 2

标准库std::complex用法更简洁,直接支持+、==、!=、+=运算符。 推断:成员函数 / 友元函数和运算符重载内在关联;运算符本质就是封装好的函数,语法糖简化调用。

问题 3

① 不是必须。普通非成员函数也可以实现,只要给 Complex 提供 public 的real()、imag()接口读取数据,不用访问私有成员。

② std::complex 的 abs不是友元,它是独立的泛型函数。

链接:https://en.cppreference.com/w/cpp/numeric/complex/abs

③ friend 仅在需要直接访问私有成员、又不适合做成成员函数时使用。优先用公有接口;友元破坏封装,少用,只用来解决运算符重载、跨类协作等特殊场景。

实验任务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 <iostream>
#include <cctype>

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 c) { return std::tolower(c); });

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

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

运行截图

6

问题

const 成员函数仅禁止修改当前对象的非静态成员;total_cnt 是静态成员,归属于类而非对象,不受 this 的 const 限制,因此可以自增。

实验任务4

源代码

Fraction.h

#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;
    // 内部工具:求最大公约数、约分、规范化(负号放分子)
    static int gcd(int a, int b);
    void normalize();
};

Fraction.cpp

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

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

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

void Fraction::normalize() {
    if (down == 0) {
        throw std::invalid_argument("Fraction: 分母不能为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) {
    normalize();
}

Fraction::Fraction(int up0, int down0) : up(up0), down(down0) {
    normalize();
}

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.up << "/" << f.down;
}

Fraction add(const Fraction& a, const Fraction& b) {
    int new_up = a.up * b.down + b.up * a.down;
    int new_down = a.down * b.down;
    return Fraction(new_up, new_down);
}

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

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

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

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

运行截图

7

问题

选用方案 1,分数类 + 友元函数。

理由:运算函数需要直接访问分子、分母私有成员,友元可以绕过公开接口直接访问内部数据,代码简洁;add/sub/mul/output 和分数类耦合度高,友元语义匹配;也是分数类实验的经典实现方式。

 

实验总结

本次实验完成了分数类的实现,使用友元函数实现分数运算与输出。我学会了私有成员的封装,了解友元函数的作用,也踩了头文件路径写错、语法笔误这些坑,明白了文件存放位置对编译的影响。

我也有一些疑问:友元会破坏封装,哪些场景不适合用友元?除法运算除零的检查是否还需要额外处理。

这次实验让我感受到写面向对象代码要先想好方案,调试的时候要仔细看报错信息。

posted @ 2026-11-19 22:44  wanqiu11  阅读(3)  评论(0)    收藏  举报