实验2_CPP

实验任务1

源代码

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

T.h

#ifndef _T_H_
#define _T_H_

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

#endif

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

运行测试结果

屏幕截图 2025-10-22 083731

问题回答

问题1

不能正常运行
屏幕截图 2025-10-22 084128
T.h中void func();的作用是在复制到task1.cpp中时,为func()提供声明,如果去掉则task1.cpp中会报错:func未定义。

问题2

普通构造函数的功能是在创建对象时传入函数接收到的参数,在用传入的参数实例化对象时被调用;复制构造函数的功能是用已存在的同类对象的数据初始化一个新的对象,在形参为const引用类型 ,且实参为现有同类对象的引用时被调用;移动构造函数的功是用临时对象的资源初始化新对象,在形参为右值引用时被调用。

问题3

会报错
屏幕截图 2025-10-22 091304
头文件T.h同时被task1.cpp和T.cpp包含,而类中静态成员在头文件中被定义时,即是做了#pragma once处理,也会出现重定义的问题。

任务2

源代码

task2.cpp

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

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

Complex.cpp

#include "Complex.h"
#include <iostream>
#include <string>
#include <cmath>
  Complex(double x0 = 0.0,double y0 = 0.0) : x{x0}, y{y0} {}
  Complex(const Complex& t) : x{t.x}, y{t.y} {}

double Complex::get_real() const
{
	return x;
}
double Complex::get_imag() const
{
	return y;
}
void Complex::add(const Complex &t)
{
	x += t.x;
	y += t.y;
}
void output(const Complex& t)
{
	std::cout << t.x << ' ';
	if (t.y >= 0.0)
		std::cout << '+' << ' ' << t.y << 'i';
	else
		std::cout << '-' << ' ' << t.y * (-1) << 'i';
}
double abs(const Complex& t)
{
	return sqrt(pow(t.x, 2) + pow(t.y, 2));
}

Complex add(const Complex& t1, const Complex& t2)
{
	Complex temp(t1.x + t2.x, t1.y + t2.y);
	return temp;
}

bool is_equal(const Complex& t1, const Complex& t2)
{
	if ((t1.x == t2.x) && (t1.y == t2.y))
		return true;
		return false;
}

bool is_not_equal(const Complex& t1, const Complex& t2)
{
	if ((t1.x != t2.x) || (t1.y != t2.y))
		return true;
	return false;
}
std::string Complex::doc = "Long Live The Republic!";

Complex.h

#ifndef _COMPLEX_H_
#define _COMPLEX_H_

#include <string>
class Complex
{
public:
	Complex(double x0 = 0.0,double y0 = 0.0){}
	Complex(const Complex& t);
	double get_real() const;
	double get_imag() const;
	void add(const Complex &t);

	friend void output(const Complex &t);
	friend double abs(const Complex &t);
	friend Complex add(const Complex& t1, const Complex& t2);
	friend bool is_equal(const Complex& t1, const Complex& t2);
	friend bool is_not_equal(const Complex& t1, const Complex& t2);

	static std::string doc;
private:
	double x = 0.0;
	double y = 0.0;
};

void output(const Complex &t);
double abs(const Complex &t);
Complex add(const Complex& t1, const Complex& t2);
bool is_equal(const Complex& t1, const Complex& t2);
bool is_not_equal(const Complex& t1, const Complex& t2);


#endif // !_COMPLEX_H_

运行测试截图

屏幕截图 2025-10-23 171934

问题回答

问题1

标准库模板类complex和自定义的类Complex相比,标准库模板类的使用形式更为简洁。
函数和运算内在有紧密关联,运算符本质上是特殊的函数,通过对运算符重载,可以对多种模板类执行多种操作。

问题2

2-1

output、abs、add对私有数据的直接访问不是必要的,可以通过Complex中的get_real,get_imag接口来间接访问

2-2

std::complex没有把abs设为友元

2-3

当类外函数需要大量访问类内部的不同私有数据时,需要使用友元,以防止写大量的getter函数;当两个类是强关联的关系,一个类必须访问另一个类的核心私有成员,并且这种访问是专属的时,使用友元比使用公开的getter更为安全,可以减少获取私有数据的方式暴露。

问题3

可以将Complex的复制构造函数设为私有函数,或显式地将Complex(const Complex &t) = delete 禁止复制构造。

任务3

源代码

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

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 <iostream>
#include <algorithm>   
#include <cctype>
int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

ControlType PlayerControl::parse(const std::string& control_str) {
    std::string temp = control_str;
    std::transform(temp.begin(), temp.end(), temp.begin(), [](unsigned char c) {return std::tolower(c); });
    ControlType res;
    if (temp == "play")
        res = ControlType::Play;
    else if (temp == "pause")
        res = ControlType::Pause;
    else if (temp == "next")
        res = ControlType::Next;
    else if (temp == "prev")
        res = ControlType::Prev;
    else if (temp == "stop")
        res = ControlType::Stop;
    else
        res = ControlType::Unknown;

    total_cnt++;
    return res;
}
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;
}

int total_cnt = 0;

运行测试结果

屏幕截图 2025-10-25 112432

实验4

源代码

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

Fraction.h

#pragma once
#include <string>
class Fraction
{
public:
	Fraction(int up0 = 0,int down0 = 1);
	Fraction(const Fraction& t);
	int get_up() const;
	int get_down() const;
	Fraction negative();
private:
	int up;
	int down;
public:
	static std::string doc;
	friend void output(const Fraction& t);
	friend Fraction add(const Fraction& t1, const Fraction& t2);
	friend Fraction sub(const Fraction& t1, const Fraction& t2);
	friend Fraction mul(const Fraction& t1, const Fraction& t2);
	friend Fraction div(const Fraction& t1, const Fraction& t2);

};

void output(const Fraction &t);
Fraction add(const Fraction& t1, const Fraction& t2);
Fraction sub(const Fraction& t1, const Fraction& t2);
Fraction mul(const Fraction& t1, const Fraction& t2);
Fraction div(const Fraction& t1, const Fraction& t2);

Fraction.cpp

#include "Fraction.h"
#include <cstdlib>
#include <iostream>
int gcd(int a, int b)
{
	a = std::abs(a);
	b = std::abs(b);
	while (b)
	{
		int temp = b;
		b = a % b;
		a = temp;
	}
	return a;
}
	
Fraction::Fraction(int up0, int down0) :up{ up0 }, down{ down0 } 
{
	int ml = gcd(up, down);
	up /= ml;
	down /= ml;
}
Fraction::Fraction(const Fraction& t) :up{ t.up }, down{ t.down } 
{
	int ml = gcd(up, down);
	up /= ml;
	down /= ml;
}

int Fraction::get_up() const
{
	return up;
}
int Fraction::get_down() const
{
	return down;
}
Fraction Fraction::negative()
{
	if (up == 0)
		return Fraction(up, down);
	else
		return Fraction(up * (-1), down);
}
void output(const Fraction& t)
{
	using std::cout;
	if (t.down == 0)
	{
		cout << "分母不能为0";
		return;
	}
	else if (t.up == 0)
		cout << 0;
	else if (t.down == 1)
		cout << t.up;
	else if (t.down == -1)
		cout << (-1) * t.up;
	else if (t.up * t.down > 0)
		cout << abs(t.up) << '/' << abs(t.down);
	else
		cout << '-' << abs(t.up) << '/' << abs(t.down);
}
std::string Fraction::doc = "Give Time To Civilization";

Fraction add(const Fraction& t1, const Fraction& t2)
{
	Fraction t0(t1.up * t2.down + t2.up * t1.down, t1.down * t2.down);
	return t0;
}

Fraction sub(const Fraction& t1, const Fraction& t2)
{
	Fraction t0(t1.up * t2.down - t2.up * t1.down, t1.down * t2.down);
	return t0;
}

Fraction mul(const Fraction& t1, const Fraction& t2)
{
	Fraction t0(t1.up * t2.up, t1.down * t2.down);
	return t0;
}

Fraction div(const Fraction& t1, const Fraction& t2)
{
	Fraction t0(t1.up * t2.down, t1.down * t2.up);
	return t0;
}

运行测试结果

屏幕截图 2025-10-25 152925

问题回答

使用友元的设计方案,使用友元可以直接访问类的私有数据,可以防止重复写多个getter函数。

posted @ 2025-10-25 15:41  DKZ_Oliveira  阅读(3)  评论(0)    收藏  举报