实验任务一
代码
t.h
1 #pragma once 2 3 #include <string> 4 5 // 类T: 声明 6 class T { 7 // 对象属性、方法 8 public: 9 T(int x = 0, int y = 0); // 普通构造函数 10 T(const T &t); // 复制构造函数 11 T(T &&t); // 移动构造函数 12 ~T(); // 析构函数 13 14 void adjust(int ratio); // 按系数成倍调整数据 15 void display() const; // 以(m1, m2)形式显示T类对象信息 16 17 private: 18 int m1, m2; 19 20 // 类属性、方法 21 public: 22 static int get_cnt(); // 显示当前T类对象总数 23 24 public: 25 static const std::string doc; // 类T的描述信息 26 static const int max_cnt; // 类T对象上限 27 28 private: 29 static int cnt; // 当前T类对象数目 30 31 // 类T友元函数声明 32 friend void func(); 33 }; 34 35 // 普通函数声明 36 void func();
t.cpp
1 // 类T: 实现 2 // 普通函数实现 3 4 #include "t.h" 5 #include <iostream> 6 #include <string> 7 8 using std::cout; 9 using std::endl; 10 using std::string; 11 12 // static成员数据类外初始化 13 const std::string T::doc{"a simple class sample"}; 14 const int T::max_cnt = 999; 15 int T::cnt = 0; 16 17 18 // 对象方法 19 T::T(int x, int y): m1{x}, m2{y} { 20 ++cnt; 21 cout << "T constructor called.\n"; 22 } 23 24 T::T(const T &t): m1{t.m1}, m2{t.m2} { 25 ++cnt; 26 cout << "T copy constructor called.\n"; 27 } 28 29 T::T(T &&t): m1{t.m1}, m2{t.m2} { 30 ++cnt; 31 cout << "T move constructor called.\n"; 32 } 33 34 T::~T() { 35 --cnt; 36 cout << "T destructor called.\n"; 37 } 38 39 void T::adjust(int ratio) { 40 m1 *= ratio; 41 m2 *= ratio; 42 } 43 44 void T::display() const { 45 cout << "(" << m1 << ", " << m2 << ")" ; 46 } 47 48 // 类方法 49 int T::get_cnt() { 50 return cnt; 51 } 52 53 // 友元 54 void func() { 55 T t5(42); 56 t5.m2 = 2049; 57 cout << "t5 = "; t5.display(); cout << endl; 58 }
task1.cpp
#include "t.h" #include <iostream> using std::cout; using std::endl; void test(); int main() { test(); cout << "\nmain: \n"; cout << "T objects'current count: " << T::get_cnt() << endl; } void test() { cout << "test class T: \n"; 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 << "t3 = "; t4.display(); cout << endl; cout << "T objects'current count: " << T::get_cnt() << endl; func(); }
编译结果
问题1
不能正确运行。如果去掉 t.h
中的友元声明 friend void func();
,程序将无法正确编译。原因是 func()
函数需要访问 T
类的私有成员变量 m2
,如果没有友元关系,func()
将无法访问 T
类的私有成员,导致编译错误。
问题2
T
类的构造函数和析构函数如下:
-
普通构造函数 T(int x = 0, int y = 0);
功能:创建一个 T 类的对象,允许用户指定成员变量 m1 和 m2 的初始值,默认为 0。
调用时机:当使用默认参数或提供具体参数创建对象时,如 T t1; 或 T t2(3, 4);。
复制构造函数 T(const T &t);
功能:通过已有的 T 类对象来初始化新的对象,实现成员变量的拷贝。
调用时机:当以现有对象初始化新对象时,如 T t3(t2);,或当对象以值传递方式作为函数参数或返回值时。
移动构造函数 T(T &&t);
功能:移动资源,而非复制,用于优化临时对象或右值的初始化,减少不必要的拷贝。
调用时机:当使用 std::move 转换为右值引用,或函数返回临时对象时,如 T t4(std::move(t2));。
析构函数 ~T();
功能:在对象生命周期结束时执行清理操作,如释放资源、更新静态计数器等。
调用时机:当对象超出其作用域、被显式删除或程序结束时,系统自动调用析构函数。
总结:
构造函数:用于初始化对象的成员变量,分配必要的资源。
析构函数:用于在对象销毁时释放资源,执行必要的清理工作。
问题3
不能正确编译运行。如果将静态成员变量的定义和初始化从 t.cpp
移动到 t.h
,会导致链接错误,无法正确编译。
实验任务2
代码
complex.cpp
1 #include "Complex.h" 2 3 const std::string Complex::doc = "a simplified complex class"; 4 5 Complex::Complex() : real(0.0), imag(0.0) {} 6 7 Complex::Complex(double real) : real(real), imag(0.0) {} 8 9 Complex::Complex(double real, double imag) : real(real), imag(imag) {} 10 11 Complex::Complex(const Complex& other) : real(other.real), imag(other.imag) {} 12 13 double Complex::get_real() const { 14 return real; 15 } 16 17 double Complex::get_imag() const { 18 return imag; 19 } 20 21 void Complex::add(const Complex& other) { 22 real += other.real; 23 imag += other.imag; 24 } 25 26 Complex add(const Complex& c1, const Complex& c2) { 27 return Complex(c1.real + c2.real, c1.imag + c2.imag); 28 } 29 30 31 bool is_equal(const Complex& c1, const Complex& c2) { 32 return (c1.real == c2.real) && (c1.imag == c2.imag); 33 } 34 35 bool is_not_equal(const Complex& c1, const Complex& c2) { 36 return !(is_equal(c1, c2)); 37 } 38 39 void output(const Complex& c) { 40 std::cout << c.real << (c.imag >= 0 ? " + " : " - ") << std::abs(c.imag) << "i"; 41 } 42 43 double abs(const Complex& c) { 44 return std::sqrt(c.real * c.real + c.imag * c.imag); 45 }
main.cpp
1 #include <iostream> 2 #include "Complex.h" 3 4 using std::cout; 5 using std::endl; 6 using std::boolalpha; 7 8 void test() { 9 cout << "类成员测试: " << endl; 10 cout << Complex::doc << endl; 11 12 cout << endl; 13 14 cout << "Complex对象测试: " << endl; 15 Complex c1; 16 Complex c2(3, -4); 17 const Complex c3(3.5); 18 Complex c4(c3); 19 20 cout << "c1 = "; output(c1); cout << endl; 21 cout << "c2 = "; output(c2); cout << endl; 22 cout << "c3 = "; output(c3); cout << endl; 23 cout << "c4 = "; output(c4); cout << endl; 24 cout << "c4.real = " << c4.get_real() << ", c4.imag = " << c4.get_imag() << endl; 25 26 cout << endl; 27 28 cout << "复数运算测试: " << endl; 29 cout << "abs(c2) = " << abs(c2) << endl; 30 c1.add(c2); 31 cout << "c1 += c2, c1 = "; output(c1); cout << endl; 32 33 cout << boolalpha; 34 cout << "c1 == c2 : " << is_equal(c1, c2) << endl; 35 cout << "c1 != c3 : " << is_not_equal(c1, c3) << endl; 36 37 c4 = add(c2, c3); 38 cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl; 39 } 40 41 int main() { 42 test(); 43 return 0; 44 }
complex.h
1 #ifndef COMPLEX_H 2 #define COMPLEX_H 3 4 #include <iostream> 5 #include <cmath> 6 7 class Complex { 8 public: 9 10 static const std::string doc; 11 12 Complex(); 13 Complex(double real); 14 Complex(double real, double imag); 15 Complex(const Complex& other); 16 17 double get_real() const; 18 double get_imag() const; 19 void add(const Complex& other); 20 21 22 friend Complex add(const Complex& c1, const Complex& c2); 23 friend bool is_equal(const Complex& c1, const Complex& c2); 24 friend bool is_not_equal(const Complex& c1, const Complex& c2); 25 friend void output(const Complex& c); 26 friend double abs(const Complex& c); 27 28 private: 29 double real; 30 double imag; 31 }; 32 33 #endif
编译结果
实验任务3
代码
1 #include <iostream> 2 #include <complex> 3 4 using std::cout; 5 using std::endl; 6 using std::boolalpha; 7 using std::complex; 8 9 void test() { 10 cout << "标准库模板类comple测试: " << endl; 11 complex<double> c1; 12 complex<double> c2(3, -4); 13 const complex<double> c3(3.5); 14 complex<double> c4(c3); 15 16 cout << "c1 = " << c1 << endl; 17 cout << "c2 = " << c2 << endl; 18 cout << "c3 = " << c3 << endl; 19 cout << "c4 = " << c4 << endl; 20 cout << "c4.real = " << c4.real() << ", c4.imag = " << c4.imag() << endl; 21 cout << endl; 22 23 cout << "复数运算测试: " << endl; 24 cout << "abs(c2) = " << abs(c2) << endl; 25 c1 += c2; 26 cout << "c1 += c2, c1 = " << c1 << endl; 27 cout << boolalpha; 28 cout << "c1 == c2 : " << (c1 == c2) << endl; 29 cout << "c1 != c3 : " << (c1 != c3) << endl; 30 c4 = c2 + c3; 31 cout << "c4 = c2 + c3, c4 = " << c4 << endl; 32 } 33 34 int main() { 35 test(); 36 }
编译结果
思考
构造函数:
默认构造函数:
-
complex<double> c1;
创建了一个默认的复数对象 c1,其实部和虚部均为 0。
带实部和虚部的构造函数:
complex<double> c2(3, -4);
创建了一个复数对象 c2,实部为 3,虚部为 -4。
仅带实部的构造函数:
const complex<double> c3(3.5);
创建了一个常量复数对象 c3,实部为 3.5,虚部为 0。
复制构造函数:
complex<double> c4(c3);
使用已有的复数对象 c3 初始化新的复数对象 c4。
成员函数:
获取实部和虚部:
c4.real(); c4.imag();
使用 real() 和 imag() 成员函数获取复数的实部和虚部。
算术运算符重载:
复数加法:
c1 += c2; c4 = c2 + c3;
使用了 operator+= 和 operator+ 进行复数的加法运算。
比较运算符重载:
相等和不等比较:
c1 == c2; c1 != c3;
使用了 operator== 和 operator!= 进行复数的比较。
非成员函数:
求复数的模(绝对值):
abs(c2);
使用标准库提供的 abs 函数计算复数的模。
输出运算符重载:
输出复数对象:
cout << c1;
使用了 operator<< 将复数对象直接输出到控制台面。
对比任务2:
1.代码简洁性:使用标准库complex 类,代码更加简洁,主要得益于运算符的重载,直接使用 +, +=, ==, != 等运算符,而不需要调用额外的函数。
输出方便: 标准库已经重载了输出运算符 <<,可以直接输出复数对象,而自定义类需要编写专门的 output 函数。
命名规范: 标准库的成员函数命名更为简洁,如 real() 和 imag(),相比自定义类的 get_real() 和 get_imag() 更为简练。
2.启发和思考:
运算符重载的重要性: 标准库 complex 类通过重载算术和比较运算符,使得复数的运算和比较变得直观且符合数学表达习惯。这提高了代码的可读性和可维护性。
友元函数 vs. 成员函数: 自定义的 Complex 类中,很多操作是通过友元函数实现的,而标准库 complex 类更多地使用成员函数和运算符重载。这提醒我们,在设计类时,可以充分利用成员函数和运算符重载,减少对友元函数的依赖。
输出运算符的重载: 标准库通过重载 << 运算符,直接支持复数对象的输出。自定义类可以借鉴这种设计,使得对象的输出更为方便。
实验任务4
代码
Fraction.h
1 #ifndef FRACTION_H 2 #define FRACTION_H 3 4 #include <string> 5 6 class Fraction { 7 public: 8 static const std::string doc; 9 10 // Constructors 11 Fraction(int up = 0, int down = 1); 12 Fraction(const Fraction &other); 13 14 // Interface methods 15 int get_up() const; 16 int get_down() const; 17 Fraction negative() const; 18 19 // Friend functions 20 friend void output(const Fraction &f); 21 friend Fraction add(const Fraction &f1, const Fraction &f2); 22 friend Fraction sub(const Fraction &f1, const Fraction &f2); 23 friend Fraction mul(const Fraction &f1, const Fraction &f2); 24 friend Fraction div(const Fraction &f1, const Fraction &f2); 25 26 private: 27 int up; 28 int down; 29 30 void reduce(); // Reduce the fraction to simplest terms 31 }; 32 33 #endif // FRACTION_H
Fraction.cpp
1 #include "Fraction.h" 2 #include <iostream> 3 #include <cstdlib> // For exit() 4 5 using namespace std; 6 7 // Utility function to compute GCD (greatest common divisor) 8 static int gcd(int a, int b) { 9 return b == 0 ? a : gcd(b, a % b); 10 } 11 12 // Initialize the static const doc 13 const string Fraction::doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算."; 14 15 // Constructors 16 Fraction::Fraction(int up, int down) : up(up), down(down) { 17 if (down == 0) { 18 cout << "Error: Denominator cannot be zero." << endl; 19 exit(1); 20 } 21 // Handle negative denominators 22 if (down < 0) { 23 this->up = -this->up; 24 this->down = -this->down; 25 } 26 reduce(); 27 } 28 29 Fraction::Fraction(const Fraction &other) : up(other.up), down(other.down) { 30 // No need to reduce, as other should already be reduced 31 } 32 33 // Interface methods 34 int Fraction::get_up() const { 35 return up; 36 } 37 38 int Fraction::get_down() const { 39 return down; 40 } 41 42 Fraction Fraction::negative() const { 43 return Fraction(-up, down); 44 } 45 46 // Private method to reduce the fraction to simplest terms 47 void Fraction::reduce() { 48 int gcd_val = gcd(abs(up), abs(down)); 49 if (gcd_val != 0) { 50 up /= gcd_val; 51 down /= gcd_val; 52 } 53 } 54 55 // Friend functions 56 void output(const Fraction &f) { 57 if (f.down == 1) { 58 cout << f.up; 59 } else { 60 cout << f.up << "/" << f.down; 61 } 62 } 63 64 Fraction add(const Fraction &f1, const Fraction &f2) { 65 int numerator = f1.up * f2.down + f2.up * f1.down; 66 int denominator = f1.down * f2.down; 67 return Fraction(numerator, denominator); 68 } 69 70 Fraction sub(const Fraction &f1, const Fraction &f2) { 71 int numerator = f1.up * f2.down - f2.up * f1.down; 72 int denominator = f1.down * f2.down; 73 return Fraction(numerator, denominator); 74 } 75 76 Fraction mul(const Fraction &f1, const Fraction &f2) { 77 int numerator = f1.up * f2.up; 78 int denominator = f1.down * f2.down; 79 return Fraction(numerator, denominator); 80 } 81 82 Fraction div(const Fraction &f1, const Fraction &f2) { 83 if (f2.up == 0) { 84 cout << "Error: Division by zero." << endl; 85 exit(1); 86 } 87 int numerator = f1.up * f2.down; 88 int denominator = f1.down * f2.up; 89 if (denominator < 0) { 90 numerator = -numerator; 91 denominator = -denominator; 92 } 93 return Fraction(numerator, denominator); 94 }
task4.cpp
1 #include "Fraction.h" 2 #include <iostream> 3 4 using std::cout; 5 using std::endl; 6 7 void test1() { 8 cout << "Fraction类测试: " << endl; 9 cout << Fraction::doc << endl << endl; 10 11 Fraction f1(5); 12 Fraction f2(3, -4), f3(-18, 12); 13 Fraction f4(f3); 14 cout << "f1 = "; output(f1); cout << endl; 15 cout << "f2 = "; output(f2); cout << endl; 16 cout << "f3 = "; output(f3); cout << endl; 17 cout << "f4 = "; output(f4); cout << endl; 18 Fraction f5(f4.negative()); 19 cout << "f5 = "; output(f5); cout << endl; 20 cout << "f5.get_up() = " << f5.get_up() << ", f5.get_down() = " << f5.get_down() << endl; 21 cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl; 22 cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl; 23 cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl; 24 cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl; 25 cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl; 26 } 27 28 void test2() { 29 Fraction f6(42, 55), f7(0, 3); 30 cout << "f6 = "; output(f6); cout << endl; 31 cout << "f7 = "; output(f7); cout << endl; 32 cout << "f6 / f7 = "; output(div(f6, f7)); cout << endl; 33 } 34 35 int main() { 36 cout << "测试1: Fraction类基础功能测试\n"; 37 test1(); 38 cout << "\n测试2: 分母为0测试: \n"; 39 test2(); 40 return 0; 41 }
编译结果
实验任务5
代码
account.cpp
1 #include <bits/stdc++.h> 2 #include "account.h" 3 using namespace std; 4 5 double SavingAccount::total=0; 6 SavingAccount::SavingAccount(int data,int id,double rate) 7 :id(id),balance(0),rate(rate),lastData(data),accumulation(0) 8 { 9 cout<<data<<"\t#"<<id<<"is created"<<endl; 10 } 11 12 void SavingAccount::record(int data,double amount) 13 { 14 accumulation=accumulate(data); 15 lastData=data; 16 amount=floor(amount*100+0.5)/100; 17 balance+=amount; 18 total+=amount; 19 cout<<data<<"\t#"<<id<<"\t"<<amount<<"\t"<<balance<<endl; 20 } 21 22 void SavingAccount::deposit(int data,double amount) 23 { 24 record(data,amount); 25 } 26 27 void SavingAccount::withdraw(int data,double amount) 28 { 29 if (amount>getBalance()) 30 cout<<"Error:not enough money"<<endl; 31 else 32 record(data,-amount); 33 } 34 35 void SavingAccount::settle(int data) 36 { 37 double interest=accumulate(data)*rate/365; 38 if (interest!=0) 39 record(data,interest); 40 accumulation=0; 41 } 42 void SavingAccount::show() const 43 { 44 cout<<"#"<<id<<"\tBalance:"<<balance; 45 }
account.h
1 #ifndef __ACCOUNT_H__ 2 #define __ACCOUNT_H__ 3 4 class SavingAccount{ 5 private: 6 int id; 7 double balance; 8 double rate; 9 double lastData; 10 double accumulation; 11 12 static double total; 13 14 void record(int data,double amount); 15 double accumulate(int data) const 16 { 17 return accumulation+balance*(data-lastData); 18 } 19 public: 20 SavingAccount(int data,int id,double rate); 21 int getId() const {return id;} 22 double getBalance() const {return balance;} 23 double getRate() const {return rate;} 24 static double getTotal() {return total;} 25 void deposit(int data,double amount); 26 void withdraw(int data,double amount); 27 void settle(int data); 28 void show() const; 29 }; 30 #endif
task5.cpp
1 #include "account.h" 2 #include <iostream> 3 using namespace std; 4 5 int main () 6 { 7 SavingAccount sa0(1,21325302,0.015); 8 SavingAccount sa1(1,58320212,0.015); 9 10 sa0.deposit(5,5000); 11 sa1.deposit(25,10000); 12 sa0.deposit(45,5500); 13 sa1.deposit(60,4000); 14 15 sa0.settle(90); 16 sa1.settle(90); 17 18 sa0.show();cout<<endl; 19 sa1.show();cout<<endl; 20 cout<<"Total:"<<SavingAccount::getTotal()<<endl; 21 return 0; 22 }
编译结果
改进
接口设计和数据封装
公共方法和数据访问:
方法命名:方法 settle 可以更具描述性,例如改为 calculateInterest 或 applyInterest,以清晰表示其用途。
常量成员函数:确保所有不修改成员变量的方法都被声明为 const,这有助于提高代码的可读性和安全性。
访问控制:所有数据成员都是私有的,这很好地实现了封装。
标签:std,const,对象,double,编程,int,Complex,实验,Fraction From: https://www.cnblogs.com/zm0110/p/18494459