实验二

实验二:类和对象

Task1:类 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();
}
// 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类对象数目
};

image

问题 1:t1 到 t4 分别调用了哪个构造函数?

  1. T t1; 调用带默认参数的构造函数 T(int x = 0, int y = 0),把 m1 和 m2 都初始化为 0。
  2. T t2(3, 4); 调用同一个构造函数,用传入的 3 和 4 初始化两个成员。
  3. T t3(t2); 调用拷贝构造函数 T(const T& t),把 t2 的两个成员值复制给 t3。
  4. T t4(std::move(t2)); 调用移动构造函数 T(T&& t)。这里的实现只读取 t2 的两个 int 成员,所以 t2 的值仍是 (3, 4)。

构造成功后,current_cnt 加 1。对象正常离开作用域时,析构函数 ~T() 会把计数减 1。

问题 2:把三个静态成员的定义移到 t.h 末尾,会发生什么?
image

t.cpp 和 task1.cpp 都包含 t.h,所以 T::doc、T::MAX_CNT 和 T::current_cnt 在两个目标文件里各定义了一次。#pragma once 只防止同一个源文件重复包含头文件。按原写法,把这三项的定义放在 t.cpp 即可。

问题 3:t1 到 t4 的作用域和生命期是什么?能直接访问 m1、m2 吗?

每个名字从各自的声明处起,到 test() 内层右花括号为止。正常运行时,对象构造完成后开始生存,离开内层代码块时按 t4、t3、t2、t1 的顺序析构。test() 里不能写 t1.m1 或 t1.m2,因为它们是 private 成员。代码里通过友元函数 output(t1) 读取它们,这体现了封装和访问权限控制。

问题 4:把 MAX_CNT 改成 2 后,程序会怎样?t1 会析构吗?

throw 用来抛出异常,程序会寻找匹配的 catch。创建 t3 时已经有两个对象,拷贝构造函数抛出 std::runtime_error。这次运行没有捕获到异常,程序异常终止,t1 和 t2 的析构函数都没有执行。C++ 规定,找不到匹配的 catch 时,调用 std::terminate() 前是否展开栈由实现决定。t3 构造失败,不会调用 ~T()。

image

Task2:复数类 Complex


// 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 << 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
//Complex.cpp
#include <iomanip>
#include <iostream>
#include "Complex.h"
using namespace std;
const std::string Complex::doc = "a simplified complex class";
Complex::Complex(double r,double i):real_{r},imag_{i}{}
Complex::Complex(const Complex& c):real_{c.real_},imag_{c.imag_}{}
void Complex::add(Complex c){
	real_+=c.real_;
	imag_+=c.imag_;
}
double Complex::real() const{
	return real_;
}
double Complex::imag() const{
	return imag_;
}
void output(const Complex& c){
	cout << c.real_ << "+" << c.imag_ << "i\n";
}
double abs(const Complex& c){
	return sqrt(c.real_*c.real_+c.imag_*c.imag_);
}
Complex add(Complex c1,Complex c2){
	Complex c3;
	c3.real_ = c1.real_ + c2.real_;
	c3.imag_ = c1.imag_ + c2.imag_;
	return c3;
}
bool is_equal(Complex c1,Complex c2){
	if(c1.real_==c2.real_&& c1.imag_ == c2.imag_) return true;
	return false;
}
bool is_not_equal(Complex c1,Complex c2){
	return (!is_equal(c1,c2));
}

// Complex.h
//Complex.h
#pragma once
#include <cmath>
#include <string>

using namespace std;

class Complex{
public:
	static const std::string doc;
	Complex(double r = 0.0,double i = 0.0);
	Complex(const Complex& c);
	double real() const;
	double imag() const;
	void add(Complex c);
	friend void output(const Complex& c);
	friend double abs(const Complex& c);
	friend Complex add(Complex c1,Complex c2);
	friend bool is_equal(Complex c1,Complex c2);
	friend bool is_not_equal(Complex c1,Complex c2);
private:
	double real_;
	double imag_;
};

image

问题 1:const 对象 c6 能调用哪些成员函数?

  1. real() 和 imag() 的声明和定义都要在参数列表后加 const,例如 double real() const。少了这个 const,编译器会报错,因为 c6 是常量对象,不能调用这两个非 const 成员函数。
  2. c6.add(c2) 不能通过编译。成员函数 add() 要修改当前对象的实部和虚部,因此是非 const 成员函数。这是 const 对象的保护机制。

问题 2:哪种复数写法更简洁?运算符和函数有什么关系?

我觉得 std::complex 更简洁,像 c2 + c3、c1 == c2 和 cout << c1 都和普通运算的写法一致。这些运算符可以通过重载实现。例如,c2 + c3 会调用对应的 operator+ 函数。

问题 3(1):output()、abs() 和非成员版 add() 必须声明为友元吗?

可以写成普通非成员函数。通过公开的 real() 和 imag() 就能取得实部和虚部,完成输出和取模。add() 把两个实部、两个虚部分别相加,再用这两个结果构造一个新的 Complex 对象。

Task3:播放器控制类 PlayerControl

//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();
}
//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 <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 str = control_str;//不能是空的 
    std::transform(control_str.begin(), control_str.end(),str.begin(),[](unsigned char c){return tolower(c);});//不能直接传给tolower 
	if(str=="play") return ControlType::Play;
	if(str=="pause") return ControlType::Pause;
	if(str=="next") return ControlType::Next;
	if(str=="prev") return ControlType::Prev;
	if(str=="stop") return ControlType::Stop;
	return ControlType::Unknown;
}

void PlayerControl::execute(ControlType cmd) const {
    // 每执行一次控制操作(含未知命令),total_cnt自增 1
    ++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;
}

image

为什么 execute() 是 const 成员函数,还能执行 ++total_cnt?

execute() 的 const 限制的是通过 this 修改当前对象的普通成员。total_cnt 是 static 成员,整个类共用同一份计数,所以每次调用 execute() 都可以把它加 1。

Task4:分数类 Fraction


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

//Fraction.h
#pragma once
#include <string>

class Fraction {
public:
	//类属性 
    static const std::string doc;
    
	//构造函数  
    Fraction(int up = 0, int down = 1);
    Fraction(const Fraction& f);
    
	//接口 
    int get_up() const;
    int get_down() const; 
    Fraction negative() const;

    //友元工具函数 
    friend void output(const Fraction& f);
    friend Fraction add(const Fraction& f1, const Fraction& f2);
    friend Fraction sub(const Fraction& f1, const Fraction& f2);
    friend Fraction mul(const Fraction& f1, const Fraction& f2);
    friend Fraction div(const Fraction& f1, const Fraction& f2);
	
	//化简
	void simplify(); 
private:
    int up;
    int down;
};

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

using namespace std;

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

//构造函数 
Fraction::Fraction(int up0, int down0) : up(up0), down(down0) {
    if (down == 0) {
        throw invalid_argument("Fraction: 分母不能为0");
    }
    simplify(); //构造时立刻化简
}
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);
}

//工友元工具函数  
//PS:用引用传效率更高,后同 
void output(const Fraction& f) {
    //如果分母为1,直接输出分子
    if (f.down == 1) {
        cout << f.up;
    } else {
        cout << f.up << "/" << f.down;
    }
}

//加 (a/b + c/d = (ad+bc)/bd) 
Fraction add(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.down + f2.up * f1.down, f1.down * f2.down);
}

//减 (a/b - c/d = (ad-bc)/bd) 
Fraction sub(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.down - f2.up * f1.down, f1.down * f2.down);
}

//乘 (a/b * c/d = ac/bd)
Fraction mul(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.up, f1.down * f2.down);
}

//除 (a/b / c/d = ad/bc)
Fraction div(const Fraction& f1, const Fraction& f2) {
    if (f2.up == 0) {//因为 b和 d既然构造出来就肯定不会是 0了 ,所以只需检查 c 
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    return Fraction(f1.up * f2.down, f1.down * f2.up);
}
//递归 
int gcd(int a, int b) {
    if(b == 0) return a;
    else return gcd(b, a%b);
}
//化简分数、处理符号
void Fraction::simplify() {
    if(up == 0) {
        down = 1;//因为当分母为 1时,会直接输出分子 
        return;
    }
    //符号都放在分子上
    if(down < 0) {
        up = -up;
        down = -down;
    }
    int g = gcd(abs(up), abs(down));//求最大公因子 
    up /= g;
    down /= g;
}

image

选择哪种设计方案?为什么?

这里我选方案一,把 output、add、sub、mul 和 div 写成友元函数。这些函数可以直接读取私有的分子和分母,四则运算可以用统一的 add(f1, f2) 这类形式,原测试代码也能沿用。运算结果交给构造函数统一处理约分和分母符号。

posted @ 2026-11-19 21:47  Mrfool0  阅读(6)  评论(0)    收藏  举报