实验2 现代C++编程初体验

任务1

源代码

T.h

#pragma once

#include <string>

// 类T: 声明
class T {
// 对象属性、方法
public:
    T(int x = 0, int y = 0);   // 普通构造函数
    T(const T &t);  // 复制构造函数
    T(T &&t);       // 移动构造函数
    ~T();           // 析构函数

    void adjust(int ratio);      // 按系数成倍调整数据
    void display() const;           // 以(m1, m2)形式显示T类对象信息

private:
    int m1, m2;

// 类属性、方法
public:
    static int get_cnt();          // 显示当前T类对象总数

public:
    static const std::string doc;       // 类T的描述信息
    static const int max_cnt;           // 类T对象上限

private:
    static int cnt;         // 当前T类对象数目

// 类T友元函数声明
    friend void func();
};

// 普通函数声明
void func();

T,cpp

#include "T.h"
#include <iostream>
#include <string>

// 类T实现

// static成员数据类外初始化
const std::string T::doc{"a simple class sample"};
const int T::max_cnt = 999;
int T::cnt = 0;

// 类方法
int T::get_cnt() {
   return cnt;
}

// 对象方法
T::T(int x, int y): m1{x}, m2{y} { 
    ++cnt; 
    std::cout << "T constructor called.\n";
} 

T::T(const T &t): m1{t.m1}, m2{t.m2} {
    ++cnt;
    std::cout << "T copy constructor called.\n";
}

T::T(T &&t): m1{t.m1}, m2{t.m2} {
    ++cnt;
    std::cout << "T move constructor called.\n";
}    

T::~T() {
    --cnt;
    std::cout << "T destructor called.\n";
}           

void T::adjust(int ratio) {
    m1 *= ratio;
    m2 *= ratio;
}    

void T::display() const {
    std::cout << "(" << m1 << ", " << m2 << ")" ;
}     

// 普通函数实现
void func() {
    T t5(42);
    t5.m2 = 2049;
    std::cout << "t5 = "; t5.display(); std::cout << '\n';
}

task1.cpp

#include "T.h"
#include <iostream>

void test_T();

int main() {
    std::cout << "test Class T: \n";
    test_T();

    std::cout << "\ntest friend func: \n";
    func();
}

void test_T() {
    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 = "; t1.display(); cout << endl;

    T t2(3, 4);
    cout << "t2 = "; t2.display(); cout << endl;

    T t3(t2);
    t3.adjust(2);
    cout << "t3 = "; t3.display(); cout << endl;

    T t4(std::move(t2));
    cout << "t4 = "; t4.display(); cout << endl;

    cout << "test: T objects'current count: " << T::get_cnt() << endl;
}

运行结果截图

屏幕截图 2025-10-28 221555

问题1

不能,友元函数的声明需满足 “先声明,后使用”。在类内部声明func为友元时,编译器需要知道func的函数原型。若删除类外部的void func();声明,类内部的友元声明会因找不到func的完整原型而报错。

屏幕截图 2025-10-28 222855

问题2

普通构造函数功能:初始化对象的成员变量(如xy),是对象创建时的默认初始化方式。调用时机:当使用T t;(默认参数)或T t(3,4);(显式传参)创建对象时调用。

复制构造函数功能:用一个已存在的对象t初始化新对象,复制t的成员变量值到新对象。调用时机:当对象被复制时(如T t2 = t1;、函数参数按值传递对象、函数返回对象时)调用。

移动构造函数功能:“窃取” 临时对象(右值)的资源,避免不必要的复制,提高效率。调用时机:当用临时对象(如函数返回的匿名对象)初始化新对象时调用。

析构函数功能:释放对象占用的资源(如动态内存、文件句柄等),完成对象销毁前的清理工作。调用时机:当对象生命周期结束时(如局部对象出作用域、动态分配的对象被delete时)自动调用。

问题3

不能屏幕截图 2025-10-28 223521

C++ 中,类的静态成员的定义只能出现一次。若将其剪切到T.h中,当T.h被多个源文件包含时,会导致静态成员在多个目标文件中被重复定义,链接阶段会报错提示 “multiple definition of T::doc” 

任务2

源代码

complex.h

#ifndef COMPLEX_H
#define COMPLEX_H

#include <string>

class Complex {
public:
    static const std::string doc;

    Complex();
    Complex(double real);
    Complex(double real, double imag);
    Complex(const Complex& other);

    double get_real() const;
    double get_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;
};

#endif

complex.cpp

#include "Complex.h"
#include <iostream>
#include <cmath>  
const std::string Complex::doc = "a simplified complex class";
Complex::Complex() : real(0.0), imag(0.0) {}
Complex::Complex(double real) : real(real), imag(0.0) {}
Complex::Complex(double real, double imag) : real(real), imag(imag) {}
Complex::Complex(const Complex& other) : real(other.real), imag(other.imag) {}

double Complex::get_real() const {
    return real;
}

double Complex::get_imag() const {
    return imag;
}

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

void output(const Complex& c) {
    if (c.imag >= 0) {
        std::cout << c.real << " + " << c.imag << "i";
    } else {
        std::cout << c.real << " - " << -c.imag << "i";  
    }
}
double abs(const Complex& c) {
    // 复数模长公式:sqrt(real2 + imag2)
    return std::sqrt(c.real * c.real + c.imag * c.imag);
}
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.cpp

#include "Complex.h"
#include <iostream>
#include <iomanip>
#include <complex>

void test_Complex();
void test_std_complex();

int main() {
    std::cout << "*******测试1: 自定义类Complex*******\n";
    test_Complex();

    std::cout << "\n*******测试2: 标准库模板类complex*******\n";
    test_std_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);

    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.real = " << c5.get_real() 
         << ", c5.imag = " << c5.get_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;
}

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;
    const std::complex<double> c5(3.5);

    cout << "c1 = " << c1 << endl;
    cout << "c2 = " << c2 << endl;
    cout << "c3 = " << c3 << endl;
    cout << "c4 = " << c4 << endl;

    cout << "c5.real = " << c5.real() 
         << ", c5.imag = " << c5.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;
}

运行结果截图

屏幕截图 2025-10-28 224945

屏幕截图 2025-10-28 225010

问题1

标准库模板类std::complex更简洁。

原因:标准库类直接支持运算符重载和流输出,语法更贴近自然数学表达;而自定义Complex需通过成员函数(add)或全局函数实现。
问题2
是。output需要访问私有成员realimag以格式化输出;abs需要计算realimag的平方和;add需要获取两个复数的realimag才能计算和。这些函数必须访问私有数据,因此需要声明为友元。
否,查阅 cppreference 可知,std::abs对于std::complex的重载是全局函数,通过complex的公有成员函数(如real()imag())获取实部和虚部,而非通过友元访问私有数据。
 以下情况考虑使用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);   // 实现std::string --> ControlType转换
    void execute(ControlType cmd) const;   // 执行控制操作(以打印输出模拟)       

    static int get_cnt();

private:
    static int total_cnt;   
};

PlayerControl.cpp

#include "PlayerControl.h"
#include <string>
#include <iostream>  

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

ControlType PlayerControl::parse(const std::string& control_str) {
    // 将输入字符串转换为小写
    std::string lower_str;
    for (char c : control_str) {
        lower_str += static_cast<char>(tolower(c));
    }

    // 匹配转换后的字符串并返回对应的枚举值
    if (lower_str == "play") {
        total_cnt++;
        return ControlType::Play;
    } else if (lower_str == "pause") {
        total_cnt++;
        return ControlType::Pause;
    } else if (lower_str == "next") {
        total_cnt++;
        return ControlType::Next;
    } else if (lower_str == "prev") {
        total_cnt++;
        return ControlType::Prev;
    } else if (lower_str == "stop") {
        total_cnt++;
        return ControlType::Stop;
    } else {
        total_cnt++;
        return ControlType::Unknown;
    }
}

void PlayerControl::execute(ControlType cmd) const {
    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 "PlayerControl.h"
#include <iostream>

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

 

运行结果截图
屏幕截图 2025-10-28 232628

 

 
任务4
源代码
Fraction.h
#ifndef FRACTION_H
#define FRACTION_H

#include <string>

class Fraction {
public:
    static const std::string doc; 
    Fraction(int up = 0);
    Fraction(int up, int down);
    Fraction(const Fraction& other);
    int get_up() const;
    int get_down() const;
    Fraction negative() const;

private:
    int up_;  
    int down_; 
    void simplify();
    static int gcd(int a, int b);
};

namespace FractionUtil {
    void output(const Fraction& f);
    Fraction add(const Fraction& f1, const Fraction& f2);
    Fraction sub(const Fraction& f1, const Fraction& f2);
    Fraction mul(const Fraction& f1, const Fraction& f2);
    Fraction div(const Fraction& f1, const Fraction& f2);
}

using namespace FractionUtil; 

#endif // FRACTION_H

Fraction.cpp

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

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

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::simplify() {
    if (down_ == 0) {
        throw std::invalid_argument("分母不能为0");
    }
    if (down_ < 0) {
        up_ *= -1;
        down_ *= -1;
    }
    int common = gcd(up_, down_);
    if (common != 0) {
        up_ /= common;
        down_ /= common;
    }
}
Fraction::Fraction(int up) : up_(up), down_(1) {
    simplify();
}

Fraction::Fraction(int up, int down) : up_(up), down_(down) {
    simplify();
}

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_);
}
namespace FractionUtil {
    void output(const Fraction& f) {
        std::cout << f.get_up() << "/" << f.get_down();
    }

    Fraction add(const Fraction& f1, const Fraction& f2) {
        int new_up = f1.get_up() * f2.get_down() + f2.get_up() * f1.get_down();
        int new_down = f1.get_down() * f2.get_down();
        return Fraction(new_up, new_down);
    }

    Fraction sub(const Fraction& f1, const Fraction& f2) {
        int new_up = f1.get_up() * f2.get_down() - f2.get_up() * f1.get_down();
        int new_down = f1.get_down() * f2.get_down();
        return Fraction(new_up, new_down);
    }

    Fraction mul(const Fraction& f1, const Fraction& f2) {
        int new_up = f1.get_up() * f2.get_up();
        int new_down = f1.get_down() * f2.get_down();
        return Fraction(new_up, new_down);
    }

    Fraction div(const Fraction& f1, const Fraction& f2) {
        if (f2.get_up() == 0) {
            throw std::invalid_argument("除数不能为0");
        }
        int new_up = f1.get_up() * f2.get_down();
        int new_down = f1.get_down() * f2.get_up();
        return Fraction(new_up, new_down);
    }
}

task4.cpp

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

void test1();
void test2();

int main() {
    std::cout << "测试1: Fraction类基础功能测试\n";
    test1();

    std::cout << "\n测试2: 分母为0测试: \n";
    test2();
}

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

 

运行结果截图
屏幕截图 2025-10-28 230710

问题

选择命名空间 + 自由函数方案。
 理由:避免友元破坏封装性,通过类的公有接口访问成员,降低耦合。比静态成员函数更符合职责单一原则,工具函数与类分离,逻辑清晰。命名空间可避免函数名冲突,便于扩展,适合集中管理相关运算功能。

 

posted @ 2025-10-28 23:27  huangyue1234  阅读(8)  评论(1)    收藏  举报