实验2

Task 1

1.运行截图
image

2.代码
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 =2;
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 t1触发了普通构造函数 t2触发了普通构造函数 t3触发了复制构造函数 t4触发了移动构造函数 普通构造函数:用户未输入参数则默认构造(0,0),若有输入参数x,y,则构造(x,y) 复制构造函数:构造一个对象与所给对象内容一样,但资源独立 移动构造函数:把原对象的内容转移给新对象,原对象资源被掏空,效率更高。

问题2

image

原因是static静态成员必须在类内声明,类外定义。剪切导致在类内定义了,所以报错

问题3

它们的作用域和生存期都是这个test()函数内部的内层大括号之内。
不能。因为私有成员只能在类内访问,这个作用域属于类外。

问题4

image
程序崩溃了。
t1属于throw出异常时同作用域内已经创建好的对象,是可以正常析构的。

Task2

image

Complex.h

点击查看代码
#ifndef COMPLEX_H
#define COMPLEX_H

#include <string>

class Complex
{
private:
    double rea;
    double ima;
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& c);

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

#endif

task2.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 ;

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

Complex.cpp

点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>

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

Complex::Complex() : rea(0), ima(0) {}
Complex::Complex(double r) : rea(r), ima(0) {}
Complex::Complex(double r, double i) : rea(r), ima(i) {}
Complex::Complex(const Complex& other) : rea(other.rea), ima(other.ima) {}

double Complex::real() const
{
    return rea;
}
double Complex::imag() const
{
    return ima;
}

void Complex::add(const Complex& c)
{
    rea += c.rea;
    ima+= c.ima;
}

void output(const Complex& c)
{
    std::cout << c.rea;
    if (c.ima > 0)
    {
        std::cout << "+" << c.ima << "i";
    }
    else if (c.ima < 0)
    {
        std::cout << c.ima << "i";
    }
    else // imag=0,只输出实部
    {
        // 什么都不追加
    }
}

double abs(const Complex& c)
{
    return sqrt(c.rea * c.rea + c.ima * c.ima);
}

Complex add(const Complex& c1, const Complex& c2)
{
    return Complex(c1.rea + c2.rea, c1.ima + c2.ima);
}

bool is_equal(const Complex& c1, const Complex& c2)
{
    return (c1.rea == c2.rea) && (c1.ima == c2.ima);
}

bool is_not_equal(const Complex& c1, const Complex& c2)
{
    return !is_equal(c1, c2);
}


问题1

1.必须加const关键字。不加的话,会说,const对象调用了一个非const成员函数,是非法的
2.不能。因为c6是const对象,不可以修改,体现const的只读保护机制。

问题2

标准库模板类complex更简洁。我觉得标准库模板类的运算就是开发者提前写好的函数,并且所有人都知道有这个运算。相当于开发者为用户省时间省力了。

问题3

不是必须的。可以实现相同功能,可以通过real()和imag()接口获取对象的实部和虚部。

Task 3

运行截图

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

PlayControl.cpp

点击查看代码
#include "PlayerControl.h"
#include <algorithm>
#include <cctype>
#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 c) { return std::tolower(c); });

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

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成员函数限制的是:类的对象的非静态成员

Task 4

运行截图

image

选择方案

方案1.
Fraction.h

点击查看代码
#pragma once

#include <string>


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

    
    Fraction(int up0, int down0 = 1);
    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();
    
    static int gcd(int a, int b);
};
Fraction.cpp
点击查看代码
#include "Fraction.h"

#include <iostream>
#include <stdexcept>


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


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 Fraction::reduce() {
    if (down < 0) {
        up = -up;
        down = -down;
    }
    int g = gcd(up < 0 ? -up : up, down);
    if (g > 1) {
        up /= g;
        down /= g;
    }
}

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

// 输出一个分数:分母为1时只输出整数形式(如 5、0),否则输出 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) {
    return Fraction(a.up * b.down, a.down * b.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 << "测试2:分母为0测试:\n";
    test2();
}

理由:output/add/sub/mul/div是Fraction接口的组成部分,声明为友元后可直接访问私有成员up、down,不需要借助get_up()/get_down()间接取值,更加简洁直观;同时这五个函数的声明集中在类定义内,可以使 Fraction.h 变成一个完整的接口文档。而且不容易与 std::div 等同名函数冲突。

posted @ 2026-11-18 20:56  shuiwu  阅读(5)  评论(0)    收藏  举报