实验二

实验任务1

task1

源代码

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 << ")";
}
task.h
点击查看代码
#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

image

问题

问题1:

普通构造函数:创造对象初始赋值t2

复制构造函数:在用已有的对象给创建新对象复制时候t3

移动构造函数:把旧对象转化为右值并赋值给新建对象时候t4

析构函数:对象生命周期结束后释放所占内存空间所有t

问题2:t1,t2调用时触发了普通构造函数,t3触发了复制构造函数,t4触发了移动构造函数,不能正确链接

问题3:在{}中,能,t1通过output友元特性可访问私有

问题4:throw的功能是抛出异常,中断正常的代码执行流程,并向上层报告错误,栈收到异常后会自动调用他们的析构函数

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();
}
### 问题1:
点击查看代码
#pragma once
#include<string>

class Complex{
	public:
		Complex(double x=0,double y=0);
		Complex(const Complex &c);
		Complex(Complex &&c);
		~Complex();
		
		double real()const;
		
		double imag()const;
		
		void add(const Complex &c);
		
		friend void output(const Complex &c);
		
		friend double abs(const Complex &c);
		
		friend  bool is_equal(const Complex &c,const Complex &b);
		
		friend  Complex add(const Complex &c,const Complex &b);
		
		friend  bool is_not_equal(const Complex &c,const Complex &b);
		static const std::string doc;
	
		Complex& operator=(const Complex &c) = default;
        Complex& operator=(Complex &&c) = default;

	private:
		double x1,x2;
};
#include "Complex.h"
#include<iostream>
#include<cmath>
#include<string>

   const std::string Complex::doc{"一枚可口的complexA版仿货"};
   Complex::Complex(double x,double y):x1{x},x2{y}{}
   Complex::Complex(const Complex &c):x1{c.x1},x2{c.x2}{}
   Complex::Complex(Complex &&c):x1{c.x1},x2{c.x2}{}
   Complex::~Complex(){ }
		
   double Complex::real()const{
   	return x1;
   }
		
    double Complex::imag()const{
    	return x2;
	}
		
	void Complex::add(const Complex &c){
		x1+=c.x1;
		x2+=c.x2;
	}
		
		void output(const Complex &c){
			if(c.x2>=0)
			std::cout<<c.x1<<"+"<<c.x2<<"i";
			else
			std::cout<<c.x1<<c.x2<<"i";
		}
		
	double abs(const Complex &c){
			return sqrt(c.x1*c.x1+c.x2*c.x2);
		}
		
		 bool is_equal(const Complex &c,const Complex &b){
			if(c.x1==b.x1&&c.x2==b.x2)
			   return true;
			else
			return false;
		}
		
	 Complex add(const Complex &c,const Complex &b){
			Complex a;
			a.x1=c.x1+b.x1;
			a.x2=c.x2+b.x2;
			return a;
		}
		
	 bool is_not_equal(const Complex &c,const Complex &b){
			return !is_equal(c,b);
		}
#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();
}

image

image

问题

问题1:必须加const,通过常量对象调用非 const 成员函数,可能破坏对象的常量属性
不能编译通过。因为 c6 是 const 对象,而 add() 是非 const 成员函数,且会修改对象成员(x1+=c.x1; x2+=c.x2;),const 对象不允许调用会修改自身的非 const 成员函数,同样报 discards qualifiers 错误。

这体现了类的 const 常量性保护机制:const 对象被限定为只读,编译器在编译期阻止任何可能修改它的操作,防止对象被意外篡改
问题2:
标准库模板 std::complex<T> 的使用形式更简洁。自定义类需要用 c1.add(c2)、add(c2,c3)、is_equal(c1,c2)、output(c1) 等专门命名函数,而标准库直接用 c1 += c2、c4 = c2 + c3、c1 == c2、cout << c1,用运算符表达运算与比较,更符合数学直觉,也不必记忆大量函数名。

函数和运算符存在内在关联:运算符本质就是函数,运算符重载是把自定义函数绑定到运算符上,使对象可以用中缀形式调用。add、is_equal、output 这类命名函数与 +、==、<< 运算符是同一功能的两种写法,运算符只是更自然的语法外衣;标准库正是通过重载 +、+=、==、!=、<< 等运算符实现了这种简洁写法。
问题3:
问题3:

1)不是必须声明为友元。普通非成员函数不能直接访问私有成员,可以通过类提供的公有接口real()和imag()实现相同功能
2)没有要求将std::abs声明为友元
https://en.cppreference.com/w/cpp/numeric/complex/abs?utm_source=chatgpt.com
3)
在工业开发中,只有当外部函数或其他类确实需要直接访问类的私有成员,且通过公有接口实现会明显降低效率或增加复杂度时,才考虑使用 friend。例如部分运算符重载和紧密协作的类。友元虽然使用方便,但会增加类之间的耦合,削弱封装性。因此应优先使用公有接口,仅在必要时授予友元权限。

源代码:

点击查看代码
#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;   
};
点击查看代码
#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 cmd=control_str;
  for(auto& ch:cmd){
      ch=static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
  }
    if (cmd == "play")
        return ControlType::Play;
    else if (cmd == "pause")
        return ControlType::Pause;
    else if (cmd == "next")
        return ControlType::Next;
    else if (cmd == "prev")
        return ControlType::Prev;
    else if (cmd == "stop")
        return ControlType::Stop;
    else
        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;
}
点击查看代码
#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 cmd=control_str;
  for(auto& ch:cmd){
      ch=static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
  }
    if (cmd == "play")
        return ControlType::Play;
    else if (cmd == "pause")
        return ControlType::Pause;
    else if (cmd == "next")
        return ControlType::Next;
    else if (cmd == "prev")
        return ControlType::Prev;
    else if (cmd == "stop")
        return ControlType::Stop;
    else
        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

问题

问题1:
成员函数限制的是当前对象的普通成员变量,而total_cnt是一个static静态成员变量

task4

源代码

点击查看代码
#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;
private:
    int up;
    int down;
    void simplify();
};
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);
点击查看代码
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
//求公约数 
namespace {
    int gcd(int a, int b) {
        if (a < 0) a = -a;
        if (b < 0) b = -b;

        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
if(a==0){
    return 0;
}
else return a;
    }
}


const std::string Fraction::doc =  "Fraction类 v0.01版.\n"  "目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
Fraction::Fraction(int up0, int down0) : up{up0}, down{down0} {

    if (down == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }

    simplify();
}

Fraction::Fraction(const Fraction& f) : up{f.up}, down{f.down} {
}
void Fraction::simplify() {
    if (down < 0) {
        up = -up;
        down = -down;
    }

    int g = gcd(up, down);

    up /= g;
    down /= g;
}
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) {
    if(f.get_down()==1){
        std::cout<<f.get_up();
    }
    else{
        std::cout << f.get_up() << "/" << f.get_down();
    }
    
}

Fraction add(const Fraction& f1, const Fraction& f2) {

    int numerator = f1.get_up() * f2.get_down()+ f2.get_up() * f1.get_down();

    int denominator = f1.get_down() * f2.get_down();

    return Fraction(numerator, denominator);
}

Fraction sub(const Fraction& f1, const Fraction& f2) {

    int numerator =
        f1.get_up() * f2.get_down()
        - f2.get_up() * f1.get_down();

    int denominator =
        f1.get_down() * f2.get_down();

    return Fraction(numerator, denominator);
}

Fraction mul(const Fraction& f1, const Fraction& f2) {

    int numerator =
        f1.get_up() * f2.get_up();

    int denominator =
        f1.get_down() * f2.get_down();

    return Fraction(numerator, denominator);
}
Fraction div(const Fraction& f1, const Fraction& f2) {
   
    int numerator =f1.get_up() * f2.get_down();

    int denominator =f1.get_down() * f2.get_up();

    return Fraction(numerator, denominator);

}
点击查看代码
#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();
}

image

问题

分数类+友元函数

通过友元函数可以直接访问私有成员并且方便实现运算符的重载。

总结

  1. 构造函数的区分与调用时机:普通构造函数负责用给定或默认参数初始化新对象;拷贝构造函数用同类左值逐成员复制;移动构造函数用同类右值转移资源,避免深拷贝;析构函数在对象销毁时自动调用完成清理。通过 t1、t2(3,4)、T t3(t2)、T t4(std::move(t2)) 四个对象,直观看到了四种构造函数分别被触发的过程。
  2. 静态成员的定义规则:静态成员属于整个类而非某个对象,必须 "类内声明、类外定义"。把静态成员定义直接写进头文件,会导致每个包含该头文件的翻译单元都生成一份定义,链接时出现 multiple definition 错误;#pragma once 只能防止同一文件重复包含,无法避免跨翻译单元的重复。
  3. const 的保护作用:const 对象只能调用 const 成员函数。real()、imag() 必须声明为 const 才能被 const 对象调用;对 const 对象调用会修改自身的非 const 成员函数(如 add)会被编译器拒绝,这是编译期的只读保护,能有效防止对象被意外修改。
  4. 运算符重载与标准库对比:通过对比自定义 Complex 与 std::complex<T>,体会到运算符本质上就是函数,运算符重载只是把函数绑定到运算符上。标准库重载了 +、+=、==、!=、<< 等运算符,使运算和比较可以直接写成 c1 += c2、c1 == c2、cout << c1,比命名函数更简洁、更符合数学直觉。
posted @ 2026-11-19 21:42  d111kkk  阅读(5)  评论(0)    收藏  举报