实验2
任务1
- 源代码:
点击查看代码
//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 << ")";
}
//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();
}
-
运行测试截图:
![image]()
-
问题回答:
1.line7是提供了默认形参的普通构造函数,在直接创建类的对象时被调用,line8为复制构造函数,复制已有的类的对象以构造新的的对象,line9是移动构造函数,将已构造的对象的对应内存分配给新的对象,line10为析构函数,在类的对象生命周期结束时用以释放内存;t1、t2调用的都是line7的函数,t1使用了默认的形参,t3使用了line8的函数,t4使用了line9的函数。
2.
能正常运行
3.t1-t4的作用域和生命期是从line14-line29,不能直接通过t1访问其私有成员m1、m2,但可以通过成员函数adjust来修改m1、m2的值,这体现了类的封装特性。
4.
崩溃了,不会销毁,运行截图中没有出现“T destructor called.”证明析构函数没有被调用
任务2
- 源代码:
点击查看代码
//Complex.h
#pragma once
#include<string>
class Complex{
public:
Complex(double m=0.0,double n=0.0) ;
Complex(const Complex &x);
double real() const;
double imag() const;
void add(const Complex &x);
friend void output(const Complex &x);
friend double abs(const Complex &x);
friend Complex add(const Complex &x,const Complex &y) ;
friend bool is_equal(const Complex &x,const Complex &y);
friend bool is_not_equal(const Complex &x,const Complex &y);
static const std::string doc; /*类的描述信息*/
private:
double m_real,m_imag; //对象数据成员
};
//Complex.cpp
#include "Complex.h"
#include<iostream>
#include<string>
#include<cmath>
//类成员初始化
const std::string Complex::doc{"a simplified complex class"};
//对象方法
Complex::Complex(double m,double n):m_real{m},m_imag{n}{
}
Complex::Complex(const Complex &x):m_real{x.m_real},m_imag{x.m_imag}{
}
double Complex::real() const{
return m_real;
}
double Complex::imag() const{
return m_imag;
}
void Complex::add(const Complex &x){
m_real+=x.m_real;
m_imag+=x.m_imag;
}
//友元函数
void output(const Complex &x){
if(x.m_imag>=0){
std::cout<< x.m_real <<"+"<< x.m_imag <<"i"<<std::endl;
}else{
std::cout<< x.m_real <<"-"<< -x.m_imag <<"i"<<std::endl;
}
}
double abs(const Complex &x){
return std::hypot(x.m_real,x.m_imag);
}
Complex add(const Complex &x,const Complex &y){
Complex t1(x),t2(y);
t1.add(t2);
return t1;
}
bool is_equal(const Complex &x,const Complex &y){
if(x.m_real==y.m_real&&x.m_imag==y.m_imag){
return true;
}else{
return false;
}
}
bool is_not_equal(const Complex &x,const Complex &y){
return !(is_equal(x,y));
}
//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();
}
-
运行测试截图:
![image]()
-
问题回答:
1.加const关键字,不加的话编译器会提示找不到对应的const成员函数;不能通过,const对象初始化后就不能再被修改,编译器会显示“const Complex”的对象不能作为this指针传递给add函数,体现了类的不可变性,常量对象只能调用const函数。
2.标准库更简洁;运算可能也是一种封装好的函数?
3.不是必须的,能实现相同的功能,只需要通过调用real()和image()函数同样可以获得对象real和imag的值。
不是,https://en.cppreference.com/cpp/numeric/complex
由于友元对类封装性的破环,导致在大部分情况下都会避免使用友元。使用友元通常是无可奈何的备用选择,如果有其他选择通常都会避免使用友元,使用友元也要注意加以限定。在较为底层的结构中,由于其本身集中,且接触的人少,风险较为可控,才会使用以减少接口开销。这些是由于友元对于类封装性的破坏与尽量减少类内部暴露的思想相悖所导致的,以及友元的使用者难以追踪,一旦使用容易出现问题,不利于长期的维护。
任务3
- 源代码:
点击查看代码
#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();
}
点击查看代码
#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 s=control_str;
std::transform(s.begin(),s.end(),s.begin(),[](unsigned char c){return std::tolower(c);}) ;
if(s=="play"){
return ControlType::Play;
}else if(s=="pause"){
return ControlType::Pause;
}else if(s=="next"){
return ControlType::Next;
}else if(s=="prev"){
return ControlType::Prev;
}else if(s=="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]()
-
问题回答:
total_cnt为全局数据类型,描述的是类的属性,而不是属于某一对象的,即使对象是const对象,仍然可以改变total_cnt的值 -
思考:
task3.cpp
点击查看代码
#include <iostream>
#include<windows.h>
#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() {
SetConsoleOutputCP(CP_UTF8);
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 s=control_str;
std::transform(s.begin(),s.end(),s.begin(),[](unsigned char c){return std::tolower(c);}) ;
if(s=="play"){
return ControlType::Play;
}else if(s=="pause"){
return ControlType::Pause;
}else if(s=="next"){
return ControlType::Next;
}else if(s=="prev"){
return ControlType::Prev;
}else if(s=="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 << "\xF0\x9F\x8E\xB5" << " Playing music...\n"; break; //emoji,中文等须由UTF-8码转义
case ControlType::Pause: std::cout << "[Pause] Music paused\n"; break;
case ControlType::Next: std::cout << "\xE2\x8F\xAD\xEF\xB8\x8F" << " Skipping to next track\n"; break;
case ControlType::Prev: std::cout << "\xE2\x8F\xAE\xEF\xB8\x8F" << " Back to previous track\n"; break;
case ControlType::Stop: std::cout << "\xE2\x8F\xB9\xEF\xB8\x8F" << " Music stopped\n"; break;
default: std::cout << "[Error] unknown control\n"; break;
}
}
int PlayerControl::get_cnt() {
return total_cnt;
}

任务4
- 源代码:
Fraction.h
点击查看代码
#pragma once
#include<string>
class Fraction{
public:
Fraction(int x,int y=1);
Fraction(const Fraction &x);
int get_up() const;
int get_down() const;
Fraction negative() const;
Fraction turn() const;
static const std::string doc;
private:
int up,down;
};
namespace tools{
void output(const Fraction &x);
Fraction add(const Fraction &x,const Fraction &y);
Fraction sub(const Fraction &x,const Fraction &y);
Fraction mul(const Fraction &x,const Fraction &y);
Fraction div(const Fraction &x,const Fraction &y);
int gcd(int a, int b);
void simplify(int &x,int &y);
int lcm(int a, int b);
};
Fraction.cpp
点击查看代码
#include<iostream>
#include<string>
#include<cstdlib>
#include<stdexcept>
#include "Fraction.h"
using namespace tools;
int tools::gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
void tools::simplify(int &x,int &y){
int a=x,b=y;
int m=gcd(a,b);
x=x/m;
y=y/m;
}
int tools::lcm(int a, int b) {
if (a == 0 || b == 0) return 0;
return std::abs(a / gcd(a, b) * b);
}
//
const std::string Fraction::doc{"Fraction类 v 0.01版. 目前仅支持分数对象的构造、输出、加/减/乘/除运算"} ;
//
Fraction::Fraction(int x,int y):up{x},down{y}{
if(down==0){
throw std::invalid_argument("Fraction: 分母不能为0");
}
if(tools::gcd(up,down)!=1&&x!=0){
tools::simplify(up,down);
}
}
Fraction::Fraction(const Fraction &x):up{x.up},down{x.down}{
}
int Fraction::get_up() const{
return up;
}
int Fraction::get_down() const{
return down;
}
Fraction Fraction::negative() const{
return Fraction(-up,down);
}
Fraction Fraction::turn() const{
return Fraction(down,up);
}
void tools::output(const Fraction &x){
int a,b;
a=x.get_up();
b=x.get_down();
if(a*b>0){
if(x.get_down()==1){
std::cout<< x.get_up() <<std::endl;
}else{
std::cout<< x.get_up() <<"/"<< x.get_down() <<std::endl;
}
}else if(a*b==0){
std::cout<< a <<std::endl;
}else{
if(abs(b)==1){
std::cout<< "-" << abs(a) <<std::endl;
}else{
std::cout<< "-" << abs(a) << "/" << abs(b) <<std::endl;
}
}
}
Fraction tools::add(const Fraction &x,const Fraction &y){
int a,b,c,d,e,f;
a=x.get_up();
b=x.get_down();
c=y.get_up();
d=y.get_down();
if(a!=0&&c!=0){
int m;
m=tools::lcm(c,d);
a=a*(m/b);
c=c*(m/d);
e=a+c;
f=m;
if(tools::gcd(e,f)!=1&&e!=0){
tools::simplify(e,f);
}
return Fraction(e,f);
}else if(a==0&&c!=0){
return y;
}else{
return x;
}
}
Fraction tools::sub(const Fraction &x,const Fraction &y){
return tools::add(x,y.negative());
}
Fraction tools::mul(const Fraction &x,const Fraction &y){
int a,b,c,d,e,f;
a=x.get_up();
b=x.get_down();
c=y.get_up();
d=y.get_down();
if(a!=0&&c!=0){
e=a*c;
f=b*d;
if(tools::gcd(e,f)!=1&&e!=0){
tools::simplify(e,f);
}
return Fraction(e,f);
}else{
return Fraction(0);
}
}
Fraction tools::div(const Fraction &x,const Fraction &y){
return tools::mul(x,y.turn());
}
task4.cpp
点击查看代码
#include <iostream>
#include "Fraction.h"
using namespace tools;
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 = "; tools::output(f1); cout << endl;
cout << "f2 = "; tools::output(f2); cout << endl;
cout << "f3 = "; tools::output(f3); cout << endl;
cout << "f4 = "; tools::output(f4); cout << endl;
const Fraction f5(f4.negative());
cout << "f5 = "; tools::output(f5); cout << endl;
cout << "f5.get_up() = " << f5.get_up()
<< ", f5.get_down() = " << f5.get_down() << endl;
cout << "f1 + f2 = "; tools::output(tools::add(f1, f2)); cout << endl;
cout << "f1 - f2 = "; tools::output(tools::sub(f1, f2)); cout << endl;
cout << "f1 * f2 = "; tools::output(tools::mul(f1, f2)); cout << endl;
cout << "f1 / f2 = "; tools::output(tools::div(f1, f2)); cout << endl;
cout << "f4 + f5 = "; tools::output(tools::add(f4, f5)); cout << endl;
}
void test2() {
using std::cout;
using std::endl;
Fraction f6(42, 55), f7(0, 3);
cout << "f6 = "; tools::output(f6); cout << endl;
cout << "f7 = "; tools::output(f7); cout << endl;
cout << "f6 / f7 = "; tools::output(div(f6, f7)); cout << endl;
}
int main() {
std::cout << "测试1: Fraction类基础功能测试\n";
test1();
std::cout << "\n测试2: 分母为0测试: \n";
test2();
}
截图

- 问题回答:
我选择了方案2,避免友元函数对类的封装性的破坏




浙公网安备 33010602011771号