实验2 类和对象_基础编程
1.实验任务一:
t.h:
#pragma once #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(); }; //const std::string T::doc{ "a simple class sample" }; //const int T::max_cnt = 999; //int T::cnt = 0; // 普通函数声明 void func();
t.cpp:
// 类T: 实现 // 普通函数实现 #include "t.h" #include <iostream> #include <string> using std::cout; using std::endl; using std::string; // static成员数据类外初始化 const std::string T::doc{ "a simple class sample" }; const int T::max_cnt = 999; int T::cnt = 0; // 对象方法 T::T(int x, int y): m1{x}, m2{y} { ++cnt; cout << "T constructor called.\n"; } T::T(const T &t): m1{t.m1}, m2{t.m2} { ++cnt; cout << "T copy constructor called.\n"; } T::T(T &&t): m1{t.m1}, m2{t.m2} { ++cnt; cout << "T move constructor called.\n"; } T::~T() { --cnt; cout << "T destructor called.\n"; } void T::adjust(int ratio) { m1 *= ratio; m2 *= ratio; } void T::display() const { cout << "(" << m1 << ", " << m2 << ")" ; } // 类方法 int T::get_cnt() { return cnt; } // 友元 void func() { T t5(42); t5.m2 = 2049; cout << "t5 = "; t5.display(); cout << endl; }
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(); }
运行截图:
问题一:
原因:头文件中未声明func()函数,导致task1引用头文件时未能找到func()函数。
问题二:
1.普通构造函数
功能:
用于初始化新创建的对象。
可以有零个或多个参数,用于给对象的成员变量赋初值。
调用时机:
当使用 new 关键字创建对象时。
当对象被声明并初始化时,例如 Example obj; 或 Example obj(参数); 。
2.复制构造函数
功能:
用于创建一个新对象,该对象是另一个已存在对象的副本。
它通过复制传入对象的资源来初始化新对象。
调用时机:
当一个对象以值传递的方式被传递给函数时。
当一个对象被分配给另一个对象时。
当一个对象被返回时(如果函数返回局部对象)。
当使用标准库容器时,容器可能会在内部复制对象。
当使用 std::copy 等算法时。
当使用 std::vector 等容器的 emplace_back 方法时。
3.移动构造函数
功能:
用于创建一个新对象,该对象接管另一个对象的资源。
它通过“移动”传入对象的资源来初始化新对象,而不是复制这些资源。
调用时机:
当一个对象以右值引用的方式被传递给函数时。
当一个对象被分配给另一个对象,且源对象是一个临时对象或右值时。
当一个对象被返回时,且返回的是一个局部对象或右值时。
当使用标准库容器时,容器可能会在内部移动对象。
当使用 std::move 将一个对象转换为右值时。
4.析构函数
功能:
用于在对象生命周期结束时进行清理工作。
负责释放对象所占用的资源,如动态分配的内存、文件句柄、网络连接等。
调用时机:
当一个对象离开其作用域时(例如局部对象)。
当一个动态分配的对象(使用 new 创建的对象)被删除时(使用 delete )。
当一个对象被销毁,例如当一个包含对象的容器被销毁时。
5.总结
普通构造函数负责对象的初始化。
复制构造函数负责创建一个对象的副本。
移动构造函数负责创建一个对象,并从另一个对象中转移资源。
析构函数负责在对象生命周期结束时进行资源清理。
问题三:
2.实验任务二:
Complex.h:
#include <iostream> #pragma once class Complex { public: Complex(double x=0, double y=0); Complex(const Complex& p); ~Complex(); void add(const Complex& p); double get_real() const; double get_imag() const; friend Complex add(const Complex& p1, const Complex& p2); friend bool is_equal(const Complex& p1, const Complex& p2); friend bool is_not_equal(const Complex& p1, const Complex& p2); friend void output(const Complex& p); friend double abs(const Complex& p); static const std::string doc; private: double real, imag; };
Complex.cpp:
#include "Complex.h" #include <cmath> double Complex::get_real() const { return real; } double Complex::get_imag() const { return imag; } void Complex::add(const Complex& p) { real = real + p.real; imag = imag + p.imag; } Complex::Complex(double x, double y):real{x},imag{y}{} Complex::Complex(const Complex& p):real{ p.real },imag{ p.imag }{} Complex::~Complex(){} Complex add(const Complex& p1, const Complex& p2) { return Complex(p1.real + p2.real, p1.imag + p2.imag); } bool is_equal(const Complex& p1, const Complex& p2) { if (p1.real == p2.real && p1.imag == p2.imag) { return 1; } else { return 0; } } bool is_not_equal(const Complex& p1, const Complex& p2) { if (p1.real == p2.real && p1.imag == p2.imag) { return 0; } else { return 1; } } void output(const Complex& p) { if (p.imag >= 0) { std::cout << p.real << " + " << p.imag << "i"; } else { std::cout << p.real << " - " <<(-1.0)*p.imag << "i"; } } double abs(const Complex& p) { return sqrt(p.real * p.real + p.imag * p.imag); } const std::string Complex::doc{ "a simplfified Complex class" };
task2.cpp:
// 待补足(多文件组织代码时,需要包含的头文件) #include <iostream> #include "Complex.h" using std::cout; using std::endl; using std::boolalpha; void test() { cout << "类成员测试: " << endl; cout << Complex::doc << endl; cout << endl; cout << "Complex对象测试: " << endl; Complex c1; Complex c2(3, -4); const Complex c3(3.5); Complex c4(c3); 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 << "c4.real = " << c4.get_real() << ", c4.imag = " << c4.get_imag() << endl; cout << 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 != c3 : " << is_not_equal(c1, c3) << endl; c4 = add(c2, c3); cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl; } int main() { test(); }
运行截图:
3.实验任务三:
#include <iostream> #include <complex> using std::cout; using std::endl; using std::boolalpha; using std::complex; void test() { cout << "标准库模板类comple测试: " << endl; complex<double> c1; complex<double> c2(3, -4); const complex<double> c3(3.5); complex<double> c4(c3); cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; cout << "c3 = " << c3 << endl; cout << "c4 = " << c4 << endl; cout << "c4.real = " << c4.real() << ", c4.imag = " << c4.imag() << endl; cout << 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 != c3 : " << (c1 != c3) << endl; c4 = c2 + c3; cout << "c4 = c2 + c3, c4 = " << c4 << endl; } int main() { test(); }
运行截图:
启发:
1.实验三中的代码直接引用了c++中自带的complex库,自带一些关于复数的操作。
2.有的时候可以适当引用一些库,以减少代码量。
4.实验任务四:
Fraction.h:
#pragma once #include <iostream> class Fraction { private: int up, down; /* int gcb(int a, int b) { return b == 0 ? a : gcb(b, a % b); }*/ public: Fraction(int x = 0, int y = 1); Fraction(const Fraction& p); ~Fraction(); friend void output(const Fraction &p); friend Fraction add( Fraction p1, Fraction p2); friend Fraction sub( Fraction p1, Fraction p2); friend Fraction mul(const Fraction &p1, const Fraction &p2); friend Fraction div(const Fraction &p1, const Fraction &p2); int get_up(); int get_down(); Fraction negative(); static std::string doc; }
Fraction.cpp:
#include "Fraction.h" #include <iostream> #include <algorithm> using namespace std; int ogcd(int a, int b) { if (a < b) { int c = b; b = a; a = c; } int r = a % b; while (r != 0) { a = b; b = r; r = a % b; } return b; } int igcd(int a, int b) { int sum1 = ogcd(a, b); return (a / sum1) * (b / sum1) * sum1; } std::string Fraction::doc = "Fraction类测试:\nFraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算."; Fraction::Fraction(int x, int y) { /*if (x < 0) { int a = -x; int b = ogcd(a, y); x = x / b; y = y / b; } else if (y < 0) { int a = -y; int b = ogcd(x, a); y = y / b; x = x / b; } else { int a = y; y = y / ogcd(x, a); x = x / ogcd(x, a); }*/ up = x;///ogcd(abs(up), abs(down)); down = y;///ogcd(abs(up), abs(down)); } Fraction::Fraction(const Fraction& p) :up{ p.up }, down{ p.down } {} Fraction::~Fraction() {} void output(const Fraction& p) { if (p.down == 0) { cout << "分母不能为0"; return; } if (p.up == 0) { cout << "0"; return; } if (p.down == 1) { cout << p.up; return; } int sum; if (p.up < 0) { sum = ogcd(-p.up, p.down); cout << "-" << -p.up / sum << "/" << p.down / sum; return; } else if (p.down < 0) { sum = ogcd(p.up, -p.down); cout << "-" << p.up / sum << "/" << -p.down / sum; return; } else { sum = ogcd(p.up, p.down); cout << p.up / sum << "/" << p.down / sum; return; } } Fraction add(Fraction p1, Fraction p2) { if (p1.down < 0) { p1.up = -p1.up; p1.down = -p1.down; } if (p2.down < 0) { p2.up = -p2.up; p2.down = -p2.down; } int sum2 = igcd(p1.down, p2.down); return Fraction(p1.up * (sum2 / p1.down) + p2.up * (sum2 / p2.down), sum2); } Fraction sub( Fraction p1, Fraction p2) { if (p1.down < 0) { p1.up = -p1.up; p1.down = -p1.down; } if (p2.down < 0) { p2.up = -p2.up; p2.down = -p2.down; } int sum2 = igcd(p1.down, p2.down); return Fraction(p1.up * (sum2 / p1.down) - p2.up * (sum2 / p2.down), sum2); } Fraction mul(const Fraction& p1, const Fraction& p2) { return Fraction(p1.up * p2.up, p1.down * p2.down); } Fraction div(const Fraction& p1, const Fraction& p2) { return Fraction(p1.up * p2.down, p1.down * p2.up); } int Fraction::get_up() { return up/ogcd(abs(up),abs(down)); } int Fraction::get_down() { return down/ ogcd(abs(up), abs(down)); } Fraction Fraction::negative() { return Fraction(-up,down); }
task4.cpp:
#include "Fraction.h" #include <iostream> using std::cout; using std::endl; void test1() { 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; 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() { 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() { cout << "测试1: Fraction类基础功能测试\n"; test1(); cout << "\n测试2: 分母为0测试: \n"; test2(); }
运行截图:
5.实验任务五:
account.h:
#ifndef __ACCOUNT_H__ #define __ACCOUNT_H__ class SavingAccount { private: int id; double balance; double rate; int lastDate; double accumulation; static double total; void record(int date, double amount); double accumulate(int date) const { return accumulation + balance * (date - lastDate); } public: SavingAccount(int date, int id, double rate); int getId()const { return id; } double getBalance()const { return balance; } double getRate() const { return rate; } static double getTotal() { return total; } void deposit(int date, double amount); void withdraw(int date, double amount); void settle(int date); void show() const; }; #endif
account.cpp:
#include "account.h" #include <cmath> #include <iostream> using namespace std; double SavingAccount::total = 0; SavingAccount::SavingAccount(int date, int id, double rate) :id(id), balance(0), rate(rate), lastDate(date), accumulation(0) { cout << date << "\t#" << id << "is created" << endl; } void SavingAccount::record(int date, double amount) { accumulation = accumulate(date); lastDate = date; amount = floor(amount * 100 + 0.5) / 100; //保留小数点后两位 balance += amount; total += amount; cout << date << "\t#" << id << "\t"<<amount<<"\t"<<balance << endl; } void SavingAccount::deposit(int date, double amount) { record(date, amount); } void SavingAccount::withdraw(int date, double amount) { if (amount > getBalance()) { cout << "Error: not enough money" << endl; } else { record(date, -amount); } } void SavingAccount::settle(int date) { double interest = accumulate(date) * rate / 365; if (interest != 0) { record(date, interest); } accumulation = 0; } void SavingAccount::show() const { cout << "#" << id << "\tBalance: " << balance; }
5_11.cpp:
#include "account.h" #include <iostream> using namespace std; int main() { SavingAccount sa0(1, 21325302, 0.015); SavingAccount sa1(1, 58320212, 0.015); sa0.deposit(5, 5000); sa1.deposit(25, 10000); sa0.deposit(45, 5500); sa1.withdraw(60, 4000); sa0.settle(90); sa1.settle(90); sa0.show(); cout << endl; sa1.show(); cout << endl; cout << "Tatal: " << SavingAccount::getTotal() << endl; return 0; }
运行截图:
启发:
1.可以在类的私有属性中设置函数,但是只能是类中public属性的函数才可以进行访问。
2.可以在.h 文件中定义某些简单的函数。
3.如果要在public中的调用一些函数进行操作,建议函数还是写在类中,以免报错。
4.保留小数点后两位,四舍五入操作:mount = floor(amount * 100 + 0.5) / 100;