commit e8a5ca236312dae43d72b84398c6b7b6d942383c Author: e2hang <2099307493@qq.com> Date: Mon Aug 11 00:01:30 2025 +0800 OOP HomeWork diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..0fa9536 --- /dev/null +++ b/README.MD @@ -0,0 +1,4 @@ +```cpp +面向对象程序设计(OOP) 作业相关资料 +留档 +``` \ No newline at end of file diff --git a/oop_hw1/01_面向对象程序设计上机实验一.docx b/oop_hw1/01_面向对象程序设计上机实验一.docx new file mode 100644 index 0000000..37c2934 Binary files /dev/null and b/oop_hw1/01_面向对象程序设计上机实验一.docx differ diff --git a/oop_hw1/01_面向对象程序设计上机实验一_参考答案.docx b/oop_hw1/01_面向对象程序设计上机实验一_参考答案.docx new file mode 100644 index 0000000..b6d5265 Binary files /dev/null and b/oop_hw1/01_面向对象程序设计上机实验一_参考答案.docx differ diff --git a/oop_hw1/oop_hw1_1/Func1.cpp b/oop_hw1/oop_hw1_1/Func1.cpp new file mode 100644 index 0000000..8e72ebc --- /dev/null +++ b/oop_hw1/oop_hw1_1/Func1.cpp @@ -0,0 +1,5 @@ +#include "func.h" + +int f1(int num) { + return g1(num * 2); +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_1/Func2.cpp b/oop_hw1/oop_hw1_1/Func2.cpp new file mode 100644 index 0000000..330ab40 --- /dev/null +++ b/oop_hw1/oop_hw1_1/Func2.cpp @@ -0,0 +1,8 @@ +#include "func.h" + +int g1(int num) { + return num * num; +} +int g2(int num) { + return f1(num * 3); +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_1/MyMain.cpp b/oop_hw1/oop_hw1_1/MyMain.cpp new file mode 100644 index 0000000..e0ea83d --- /dev/null +++ b/oop_hw1/oop_hw1_1/MyMain.cpp @@ -0,0 +1,7 @@ +#include +#include "func.h" +using namespace std; +int main(int argc, char * argv[]) { + cout << g2(10) << endl; + return 0; +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_1/func.h b/oop_hw1/oop_hw1_1/func.h new file mode 100644 index 0000000..61dbe38 --- /dev/null +++ b/oop_hw1/oop_hw1_1/func.h @@ -0,0 +1,9 @@ +#pragma once +#ifndef FUNC_H +#define FUNC_H + +int f1(int num); +int g1(int num); +int g2(int num); + +#endif diff --git a/oop_hw1/oop_hw1_2/main.cpp b/oop_hw1/oop_hw1_2/main.cpp new file mode 100644 index 0000000..6c836c1 --- /dev/null +++ b/oop_hw1/oop_hw1_2/main.cpp @@ -0,0 +1,14 @@ +#include +#include "print_this.h" +#include "print_that.h" +extern int print_count; + +int main() { +#ifdef DO_THIS + print_this("Hello"); +#else + print_that("Hello"); +#endif + std :: cout << "Print called " << print_count << " times." << std::endl; + return 0; +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_2/print.cpp b/oop_hw1/oop_hw1_2/print.cpp new file mode 100644 index 0000000..3e4ed5b --- /dev/null +++ b/oop_hw1/oop_hw1_2/print.cpp @@ -0,0 +1,7 @@ +#include +#include "print.h" +int print_count = 0; +void print(const std::string& s) { + ++print_count; + std::cout << s << std::endl; +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_2/print.h b/oop_hw1/oop_hw1_2/print.h new file mode 100644 index 0000000..416dcaf --- /dev/null +++ b/oop_hw1/oop_hw1_2/print.h @@ -0,0 +1,6 @@ +#pragma once +#include +#ifndef PRINT_H +#define PRINT_H +void print(const std::string& s); +#endif \ No newline at end of file diff --git a/oop_hw1/oop_hw1_2/print_that.cpp b/oop_hw1/oop_hw1_2/print_that.cpp new file mode 100644 index 0000000..50583ef --- /dev/null +++ b/oop_hw1/oop_hw1_2/print_that.cpp @@ -0,0 +1,5 @@ +#include "print.h" +#include "print_that.h" +void print_that(const std::string& s) { + print("That: " + s); +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_2/print_that.h b/oop_hw1/oop_hw1_2/print_that.h new file mode 100644 index 0000000..6b0fc90 --- /dev/null +++ b/oop_hw1/oop_hw1_2/print_that.h @@ -0,0 +1,7 @@ + +#pragma once +#include +#ifndef PRINT_THAT_H +#define PRINT_THAT_H +void print_that(const std::string& s); +#endif \ No newline at end of file diff --git a/oop_hw1/oop_hw1_2/print_this.cpp b/oop_hw1/oop_hw1_2/print_this.cpp new file mode 100644 index 0000000..b502deb --- /dev/null +++ b/oop_hw1/oop_hw1_2/print_this.cpp @@ -0,0 +1,5 @@ +#include "print.h" +#include "print_this.h" +void print_this(const std::string& s) { + print("This: " + s); +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_2/print_this.h b/oop_hw1/oop_hw1_2/print_this.h new file mode 100644 index 0000000..fb3743a --- /dev/null +++ b/oop_hw1/oop_hw1_2/print_this.h @@ -0,0 +1,6 @@ +#pragma once +#include +#ifndef PRINT_THIS_H +#define PRINT_THIS_H +void print_this(const std::string& s); +#endif \ No newline at end of file diff --git a/oop_hw1/oop_hw1_3/main.cpp b/oop_hw1/oop_hw1_3/main.cpp new file mode 100644 index 0000000..ce03686 --- /dev/null +++ b/oop_hw1/oop_hw1_3/main.cpp @@ -0,0 +1,17 @@ +#include +double average(int arr[], int size) { + int sum = 0; + for (int i = 0; i < size; ++i) sum += arr[i]; + return (double)sum / size; +} +using namespace std; +int main() { + int n; + cin >> n; + int * a = new int[n]; + for (int i = 0;i < n;i++) { + cin >> a[i]; + } + cout << average(a, n); + return 0; +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_4/main.cpp b/oop_hw1/oop_hw1_4/main.cpp new file mode 100644 index 0000000..908b3a5 --- /dev/null +++ b/oop_hw1/oop_hw1_4/main.cpp @@ -0,0 +1,11 @@ +#include +#include "t_area.h" + +using namespace std; + +int main() { + double a, b, c; + cin >> a >> b >> c; + cout << triangle_area(a,b,c) << endl; + return 0; +} diff --git a/oop_hw1/oop_hw1_4/t_area.cpp b/oop_hw1/oop_hw1_4/t_area.cpp new file mode 100644 index 0000000..fe00ef7 --- /dev/null +++ b/oop_hw1/oop_hw1_4/t_area.cpp @@ -0,0 +1,5 @@ +#include +double triangle_area(double a, double b, double c) { + double s = (a + b + c) / 2; + return sqrt(s * (s - a) * (s - b) * (s - c)); +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_4/t_area.h b/oop_hw1/oop_hw1_4/t_area.h new file mode 100644 index 0000000..e5e843c --- /dev/null +++ b/oop_hw1/oop_hw1_4/t_area.h @@ -0,0 +1,8 @@ +#pragma once +#ifndef tarea +#define tarea + +double triangle_area(double a, double b, double c); + + +#endif // !tarea diff --git a/oop_hw1/oop_hw1_5/check_num.h b/oop_hw1/oop_hw1_5/check_num.h new file mode 100644 index 0000000..5aff878 --- /dev/null +++ b/oop_hw1/oop_hw1_5/check_num.h @@ -0,0 +1,7 @@ +#pragma once +#ifndef testchar +#define testchar + +bool is_digit(char ch); + +#endif // !testchar \ No newline at end of file diff --git a/oop_hw1/oop_hw1_5/main.cpp b/oop_hw1/oop_hw1_5/main.cpp new file mode 100644 index 0000000..af0e7ee --- /dev/null +++ b/oop_hw1/oop_hw1_5/main.cpp @@ -0,0 +1,13 @@ +#include +#include "check_num.h" + +using namespace std; +int main() +{ + char ch; + for (int i = 0;i < 10;i++) { + cin >> ch; + cout << is_digit(ch)<= '0' && ch <= '9'; +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_5/测试截图1_5.jpg b/oop_hw1/oop_hw1_5/测试截图1_5.jpg new file mode 100644 index 0000000..7a5e448 Binary files /dev/null and b/oop_hw1/oop_hw1_5/测试截图1_5.jpg differ diff --git a/oop_hw1/oop_hw1_6/main.cpp b/oop_hw1/oop_hw1_6/main.cpp new file mode 100644 index 0000000..119853d --- /dev/null +++ b/oop_hw1/oop_hw1_6/main.cpp @@ -0,0 +1,16 @@ +#include +#include "sort.h" + +using namespace std; +int main() { + int d, e; + cin >> d >> e; + sort_two(d, e); + int a, b, c; + cin >> a >> b >> c; + sort_three(a, b, c); + cout << "" << endl; + cout << d << e < +void sort_two(int& a, int& b) { + if (a < b) std::swap(a, b); +} +void sort_three(int& a, int& b, int& c) { + if (a < b) std::swap(a, b); + if (a < c) std::swap(a, c); + if (b < c) std::swap(b, c); +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_6/sort.h b/oop_hw1/oop_hw1_6/sort.h new file mode 100644 index 0000000..22ef177 --- /dev/null +++ b/oop_hw1/oop_hw1_6/sort.h @@ -0,0 +1,7 @@ +#pragma once +#ifndef sort +#define sort +void sort_three(int& a, int& b, int& c); +void sort_two(int& d, int& e); + +#endif // !sort diff --git a/oop_hw1/oop_hw1_6/测试截图1_6.jpg b/oop_hw1/oop_hw1_6/测试截图1_6.jpg new file mode 100644 index 0000000..cb027d0 Binary files /dev/null and b/oop_hw1/oop_hw1_6/测试截图1_6.jpg differ diff --git a/oop_hw1/oop_hw1_7/fib.cpp b/oop_hw1/oop_hw1_7/fib.cpp new file mode 100644 index 0000000..68a00f1 --- /dev/null +++ b/oop_hw1/oop_hw1_7/fib.cpp @@ -0,0 +1,14 @@ +#include +long& smaller(long& a, long& b) { return (a < b) ? a : b; } +long& bigger(long& a, long& b) { return (a >= b) ? a : b; } + +void fibe(int count) { + long a = 1, b = 1; + for (int i = 0; i < count; i++) { + long& min = smaller(a, b); + long& max = bigger(a, b); + min = a + b; + std::cout << max << " "; + } + std::cout << std::endl; +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_7/fib.h b/oop_hw1/oop_hw1_7/fib.h new file mode 100644 index 0000000..233340d --- /dev/null +++ b/oop_hw1/oop_hw1_7/fib.h @@ -0,0 +1,9 @@ +#pragma once +#ifndef fib +#define fib + +long& smaller(long& a, long& b); +long& bigger(long& a, long& b); +void fibe(int count); + +#endif // !fib diff --git a/oop_hw1/oop_hw1_7/main.cpp b/oop_hw1/oop_hw1_7/main.cpp new file mode 100644 index 0000000..421a02e --- /dev/null +++ b/oop_hw1/oop_hw1_7/main.cpp @@ -0,0 +1,10 @@ +#include +#include "fib.h" + +using namespace std; +int main() { + int n; + cin >> n; + fibe(n); + return 0; +} \ No newline at end of file diff --git a/oop_hw1/oop_hw1_9/main.cpp b/oop_hw1/oop_hw1_9/main.cpp new file mode 100644 index 0000000..d9c8b7c --- /dev/null +++ b/oop_hw1/oop_hw1_9/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +class Pen { +public: + void write() {} +}; + +class FountainPen : public Pen { +public: + void refill() {} +}; + +class File { +public: + std::string name; +}; + +class Directory { +public: + std::vector files; +}; + +class Printer { +public: + void print(const std::string& doc) {} +}; + +class Monitor { +public: + void display(const std::string& img) {} +}; + +class Sun { +public: + void shine() {} +}; + +class Moon { +public: + void reflect() {} +}; diff --git a/oop_hw1/上机测试1 (1).pdf b/oop_hw1/上机测试1 (1).pdf new file mode 100644 index 0000000..9859b06 Binary files /dev/null and b/oop_hw1/上机测试1 (1).pdf differ diff --git a/oop_hw2/02_面向对象程序设计上机实验二.docx b/oop_hw2/02_面向对象程序设计上机实验二.docx new file mode 100644 index 0000000..4ce6eaf Binary files /dev/null and b/oop_hw2/02_面向对象程序设计上机实验二.docx differ diff --git a/oop_hw2/02_面向对象程序设计上机实验二_参考答案.docx b/oop_hw2/02_面向对象程序设计上机实验二_参考答案.docx new file mode 100644 index 0000000..4e17bb5 Binary files /dev/null and b/oop_hw2/02_面向对象程序设计上机实验二_参考答案.docx differ diff --git a/oop_hw2/oop_hw2_1/Q1.cpp b/oop_hw2/oop_hw2_1/Q1.cpp new file mode 100644 index 0000000..cf9398e --- /dev/null +++ b/oop_hw2/oop_hw2_1/Q1.cpp @@ -0,0 +1,61 @@ +#include +#include + +#include +#include + +class TRandom { +private: + unsigned long seed; +public: + TRandom(unsigned long s) : seed(s) {} + unsigned char NextByte() { + seed = seed * 1103515245 + 12345; + return static_cast((seed / 65536) % 256); + } +}; + +void Coder(unsigned char data[], int len, unsigned long key) { + TRandom rand(key); + for (int i = 0; i < len; ++i) { + data[i] ^= rand.NextByte(); + } +} + +void Coder(unsigned char data[], int len, TRandom& rand, unsigned long key) { + for (int i = 0; i < len; ++i) { + data[i] ^= rand.NextByte(); + } +} + +class Crypter { +private: + TRandom rand; +public: + Crypter(unsigned long seed) : rand(seed) {} + void Process(unsigned char data[], int len) { + for (int i = 0; i < len; ++i) { + data[i] ^= rand.NextByte(); + } + } +}; + +void Test() { + unsigned char msg[] = "Hello World"; + int len = sizeof(msg); + unsigned long key = 12345; + std::cout << "Original: " << msg << std::endl; + Coder(msg, len, key); + std::cout << "Encrypted: "; for (int i = 0; i < len; ++i) std::cout << msg[i]; std::cout << std::endl; + Coder(msg, len, key); + std::cout << "Decrypted: " << msg << std::endl; +} + + +int main(){ + Test(); + return 0; +} + +// 3 rand Ϊ TRandom randֵᶪʧԭ״̬ظʼӣ +// 4Ϊ const TRandom& randУΪ NextByte ı״̬ const diff --git a/oop_hw2/oop_hw2_1/Q1.exe b/oop_hw2/oop_hw2_1/Q1.exe new file mode 100644 index 0000000..9f94b6b Binary files /dev/null and b/oop_hw2/oop_hw2_1/Q1.exe differ diff --git a/oop_hw2/oop_hw2_1/测试截图1.png b/oop_hw2/oop_hw2_1/测试截图1.png new file mode 100644 index 0000000..7ca1931 Binary files /dev/null and b/oop_hw2/oop_hw2_1/测试截图1.png differ diff --git a/oop_hw2/oop_hw2_2/Q2.cpp b/oop_hw2/oop_hw2_2/Q2.cpp new file mode 100644 index 0000000..1fda0cd --- /dev/null +++ b/oop_hw2/oop_hw2_2/Q2.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +class Book { +private: + int totalPages; + int pagesRead; +public: + Book(int total) : totalPages(total), pagesRead(0) {} + void Read(int pages) { pagesRead += pages; if (pagesRead > totalPages) pagesRead = totalPages; } + int GetTotalPages() const { return totalPages; } + int GetPagesRead() const { return pagesRead; } + int GetPagesLeft() const { return totalPages - pagesRead; } +}; + +void Test() { + Book b(100); + b.Read(30); + std::cout << "Read: " << b.GetPagesRead() << ", Left: " << b.GetPagesLeft() << std::endl; + b.Read(80); + std::cout << "Read: " << b.GetPagesRead() << ", Left: " << b.GetPagesLeft() << std::endl; +} + +int main(){ + Test(); + return 0; +} diff --git a/oop_hw2/oop_hw2_2/Q2.exe b/oop_hw2/oop_hw2_2/Q2.exe new file mode 100644 index 0000000..a7d123d Binary files /dev/null and b/oop_hw2/oop_hw2_2/Q2.exe differ diff --git a/oop_hw2/oop_hw2_2/测试截图2.png b/oop_hw2/oop_hw2_2/测试截图2.png new file mode 100644 index 0000000..879602e Binary files /dev/null and b/oop_hw2/oop_hw2_2/测试截图2.png differ diff --git a/oop_hw2/oop_hw2_3/Q3.cpp b/oop_hw2/oop_hw2_3/Q3.cpp new file mode 100644 index 0000000..ef9e6da --- /dev/null +++ b/oop_hw2/oop_hw2_3/Q3.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +enum Suit { Spade, Heart, Diamond, Club }; +enum Rank { Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }; + +class Card { +private: + int id; + Suit suit; + Rank rank; + int backId; + int width, height; + std::pair topLeft; +public: + Card(int _id, Suit _suit, Rank _rank, int _backId, int _w, int _h, std::pair _tl) + : id(_id), suit(_suit), rank(_rank), backId(_backId), width(_w), height(_h), topLeft(_tl) {} + + Card(const Card& other) : id(other.id), suit(other.suit), rank(other.rank), backId(other.backId), + width(other.width), height(other.height), topLeft(other.topLeft) {} + + int GetBackId() const { return backId; } + void SetBackId(int id) { backId = id; } + bool IsSameSuit(const Card& other) const { return suit == other.suit; } + bool IsSameRank(const Card& other) const { return rank == other.rank; } + bool IsSuit(Suit s) const { return suit == s; } + bool IsRank(Rank r) const { return rank == r; } + void SetPosition(int x, int y) { topLeft = {x, y}; } + std::pair GetBottomRight() const { return {topLeft.first + width, topLeft.second + height}; } +}; + +void Test() { + Card c1(0, Spade, Ace, 1, 100, 150, {0, 0}); + Card c2(1, Spade, King, 2, 100, 150, {100, 0}); + std::cout << "Same Suit: " << c1.IsSameSuit(c2) << std::endl; + std::cout << "Bottom Right: (" << c1.GetBottomRight().first << ", " << c1.GetBottomRight().second << ")\n"; +} + +int main(){ + Test(); + return 0; +} diff --git a/oop_hw2/oop_hw2_3/Q3.exe b/oop_hw2/oop_hw2_3/Q3.exe new file mode 100644 index 0000000..5d328bf Binary files /dev/null and b/oop_hw2/oop_hw2_3/Q3.exe differ diff --git a/oop_hw2/oop_hw2_3/测试截图3.png b/oop_hw2/oop_hw2_3/测试截图3.png new file mode 100644 index 0000000..44bb337 Binary files /dev/null and b/oop_hw2/oop_hw2_3/测试截图3.png differ diff --git a/oop_hw2/oop_hw2_4/Q4.cpp b/oop_hw2/oop_hw2_4/Q4.cpp new file mode 100644 index 0000000..b97d424 --- /dev/null +++ b/oop_hw2/oop_hw2_4/Q4.cpp @@ -0,0 +1,51 @@ +#include +#include + +class Hero { +private: + int charm, fame, attack, defense, magic; + int items[5] = {0}; +public: + Hero() : charm(0), fame(0), attack(0), defense(0), magic(0) {} + + void Equip(int pos, int item) { + if (pos >= 0 && pos < 5) items[pos] = item; + ApplyItem(item); + } + + void Remove(int pos) { + if (pos >= 0 && pos < 5) items[pos] = 0; + } + + void ApplyItem(int item) { + switch(item) { + case 1: charm += 2; break; + case 2: fame += 3; break; + case 3: attack += 1; break; + case 4: defense += 2; break; + case 5: magic += 4; break; + case 6: charm += 1; magic += 1; break; + } + } + + void ShowStats() const { + std::cout << "Charm: " << charm << ", Fame: " << fame + << ", Attack: " << attack << ", Defense: " << defense + << ", Magic: " << magic << std::endl; + } +}; + +void Test() { + Hero h; + h.Equip(0, 1); + h.Equip(1, 3); + h.Equip(2, 5); + h.ShowStats(); + h.Remove(1); + h.ShowStats(); +} + +int main(){ + Test(); + return 0; +} diff --git a/oop_hw2/oop_hw2_4/Q4.exe b/oop_hw2/oop_hw2_4/Q4.exe new file mode 100644 index 0000000..a0578db Binary files /dev/null and b/oop_hw2/oop_hw2_4/Q4.exe differ diff --git a/oop_hw2/oop_hw2_4/测试截图4.png b/oop_hw2/oop_hw2_4/测试截图4.png new file mode 100644 index 0000000..8a179bd Binary files /dev/null and b/oop_hw2/oop_hw2_4/测试截图4.png differ diff --git a/oop_hw2/oop_hw2_5/Q5.cpp b/oop_hw2/oop_hw2_5/Q5.cpp new file mode 100644 index 0000000..f0d3df8 --- /dev/null +++ b/oop_hw2/oop_hw2_5/Q5.cpp @@ -0,0 +1,27 @@ +#include + +class Demo { +private: + int mNum; + static Demo* instance; + Demo() : mNum(0) {} +public: + static Demo* GetInstance() { + if (!instance) instance = new Demo(); + return instance; + } + void AddValue(int value) { mNum += value; } + void ShowValue() const { std::cout << "Value=" << mNum << std::endl; } +}; +Demo* Demo::instance = NULL; + +void Test() { + Demo::GetInstance()->AddValue(10); + Demo::GetInstance()->AddValue(5); + Demo::GetInstance()->ShowValue(); +} + +int main(){ + Test(); + return 0; +} diff --git a/oop_hw2/oop_hw2_5/Q5.exe b/oop_hw2/oop_hw2_5/Q5.exe new file mode 100644 index 0000000..ffd7a71 Binary files /dev/null and b/oop_hw2/oop_hw2_5/Q5.exe differ diff --git a/oop_hw2/oop_hw2_5/测试截图5.png b/oop_hw2/oop_hw2_5/测试截图5.png new file mode 100644 index 0000000..5ad0236 Binary files /dev/null and b/oop_hw2/oop_hw2_5/测试截图5.png differ diff --git a/oop_hw2/oop_hw2_6/Q6.cpp b/oop_hw2/oop_hw2_6/Q6.cpp new file mode 100644 index 0000000..b2e277e --- /dev/null +++ b/oop_hw2/oop_hw2_6/Q6.cpp @@ -0,0 +1,46 @@ +#include +using namespace std; + +class Monster { +private: + int speed, hitpoint, damage, defense; +public: + Monster(int s, int h, int d, int def) : speed(s), hitpoint(h), damage(d), defense(def) {} + + bool operator>(const Monster& other) const { + if (speed != other.speed) return speed > other.speed; + if (hitpoint != other.hitpoint) return hitpoint > other.hitpoint; + if (damage != other.damage) return damage > other.damage; + return defense > other.defense; + } + + void Attack(Monster& other) const { + int harm = std::max(2 * damage - other.defense, 1); + other.hitpoint -= harm; + std::cout << "Monster attacks for " << harm << " damage. Opponent HP: " << other.hitpoint << std::endl; + } + + void Fight(Monster& other) { + Monster* first = this; + Monster* second = &other; + if (!(*this > other)) std::swap(first, second); + + while (first->hitpoint > 0 && second->hitpoint > 0) { + first->Attack(*second); + if (second->hitpoint <= 0) break; + second->Attack(*first); + } + } +}; + +void Test() { + Monster m1(10, 30, 5, 2); + Monster m2(8, 35, 4, 3); + m1.Fight(m2); +} + +int main(){ + Test(); + return 0; +} + diff --git a/oop_hw2/oop_hw2_6/Q6.exe b/oop_hw2/oop_hw2_6/Q6.exe new file mode 100644 index 0000000..d88a2b2 Binary files /dev/null and b/oop_hw2/oop_hw2_6/Q6.exe differ diff --git a/oop_hw2/oop_hw2_6/测试截图6.png b/oop_hw2/oop_hw2_6/测试截图6.png new file mode 100644 index 0000000..f08e900 Binary files /dev/null and b/oop_hw2/oop_hw2_6/测试截图6.png differ diff --git a/oop_hw2/上机测试2.pdf b/oop_hw2/上机测试2.pdf new file mode 100644 index 0000000..7ed62ed Binary files /dev/null and b/oop_hw2/上机测试2.pdf differ diff --git a/oop_hw3/hw1/main.cpp b/oop_hw3/hw1/main.cpp new file mode 100644 index 0000000..c09d491 --- /dev/null +++ b/oop_hw3/hw1/main.cpp @@ -0,0 +1,74 @@ +#define _CRT_SECURE_NO_WARNINGS +#include +#include +using namespace std; +class MyString { +private: + char* mpData; +public: + MyString(const char* pData = nullptr) { + if (pData == nullptr) { + mpData = new char[1]; + mpData[0] = '\0'; + } + else { + int len = strlen(pData); + mpData = new char[len + 1]; + strcpy(mpData, pData); + } + + } + MyString(const MyString& x) { + int len = strlen(x.mpData); + mpData = new char[len + 1]; + strcpy(mpData, x.mpData); + } + ~MyString() { + delete[] mpData; + } + MyString& operator=(const MyString& x) { + if (this == &x) return *this; + delete[] mpData; + int len = strlen(x.mpData); + mpData = new char[len + 1]; + strcpy(mpData, x.mpData); + return *this; + } + MyString& operator+=(const MyString& x) { + int len = strlen(mpData) + strlen(x.mpData); + char* tmp = new char[len + 1]; + strcpy(tmp, mpData); + strcat(tmp, x.mpData); + delete[] mpData; + mpData = tmp; + return *this; + } + friend const MyString operator+(const MyString& x, const MyString& y) { + int len = strlen(x.mpData) + strlen(y.mpData); + char* tmp = new char[len + 1]; + strcpy(tmp, x.mpData); + strcat(tmp, y.mpData); + MyString r(tmp); + delete[] tmp; + return r; + } + friend ostream& operator<<(ostream& os, const MyString& x) { + os << x.mpData; + return os; + } +}; + +int main() { + char p[] = "Hello, world!"; + char q[] = "What are you doing?"; + char r[] = "How are you!"; + MyString a(p), b, c; + b = MyString(q); + c = b; + MyString d; + d = a + b; + cout << d << endl; + + + return 0; +} \ No newline at end of file diff --git a/oop_hw3/hw1/测试截图1.png b/oop_hw3/hw1/测试截图1.png new file mode 100644 index 0000000..c0bf217 Binary files /dev/null and b/oop_hw3/hw1/测试截图1.png differ diff --git a/oop_hw3/hw2/main.cpp b/oop_hw3/hw2/main.cpp new file mode 100644 index 0000000..4f5e03f --- /dev/null +++ b/oop_hw3/hw2/main.cpp @@ -0,0 +1,91 @@ +#include +#include +#include +#define M_PI 3.14159265358979323846 +using namespace std; +// +class Fraction { +private: + int* p; +public: + Fraction():p(nullptr){} + //ֻܴСΪ30 + Fraction(int* x) { + if (p) delete[] p; + p = new int[30]; + for (int i = 0; i < 30 ;i++) { + p[i] = x[i]; + } + } + Fraction(const Fraction& x) { + if(p) delete[] p; + p = new int[30]; + for (int i = 0; i < 30;i++) { + p[i] = x.p[i]; + } + } + Fraction& operator=(const Fraction& x) { + if(p) delete[] p; + p = new int[30]; + for (int i = 0; i < 30;i++) { + p[i] = x.p[i]; + } + } + friend ostream& operator<<(ostream& os, const Fraction& x) { + for (int i = 0;i < 30;i++) { + os << x.p[i] << " "; + } + return os; + } + ~Fraction() { + delete[] p; + } + void DuiYingFenshu(int x) { + long long fenzi = 1, fenmu = 0; + for (int i = x - 1; i >= 0; --i) { + long long temp = fenzi; + fenzi = p[i] * fenzi + fenmu; + fenmu = temp; + } + double val = (double)fenzi / fenmu; + double cha = M_PI - val; + cout << setprecision(16); + cout << "" << x << "Ӧķǣ" << fenzi << "/" << fenmu << endl; + cout << "" << x << "ӦСǣ" << val << endl; + cout << " PI " << cha << endl; + } +}; +//һСתʽ +int* out(double x) { + double t = x; + double temp; + int* tmp; + tmp = new int[30]; + tmp[0] = floor(t); + t -= tmp[0]; + for (int i = 1;i < 30;i++) { + temp = 1 / (t); + tmp[i] = floor(temp); + temp -= tmp[i]; + t = temp; + } + return tmp; +} + +int main() { + //out + int* a; + a = out(M_PI); + for (int i = 0;i < 30;i++) { + cout << a[i] << " "; + } + cout << endl; + + // + Fraction test(a); + for (int i = 1;i < 30;i++) { + test.DuiYingFenshu(i); + cout << endl; + } + return 0; +} \ No newline at end of file diff --git a/oop_hw3/hw2/测试截图2.png b/oop_hw3/hw2/测试截图2.png new file mode 100644 index 0000000..3ca7c27 Binary files /dev/null and b/oop_hw3/hw2/测试截图2.png differ diff --git a/oop_hw3/hw3/main.cpp b/oop_hw3/hw3/main.cpp new file mode 100644 index 0000000..40995e3 --- /dev/null +++ b/oop_hw3/hw3/main.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +template +void f(int m, int n) { + T** p; + p = new T* [m]; + for (int i = 0;i < m;i++) { + p[i] = new T[n]; + } + int cnt = 1; + for (int i = 0;i < m;i++) { + for (int j = 0;j < n;j++) { + p[i][j] = cnt; + cout << cnt << " "; + cnt++; + } + cout << endl; + } + if (p) { + for (int i = 0;i < m;i++) { + delete[] p[i]; + } + delete[] p; + } +} + +int main() { + int a, b; + cin >> a >> b; + f(a, b); + return 0; +} \ No newline at end of file diff --git a/oop_hw3/hw3/测试截图3.png b/oop_hw3/hw3/测试截图3.png new file mode 100644 index 0000000..b4b627d Binary files /dev/null and b/oop_hw3/hw3/测试截图3.png differ diff --git a/oop_hw3/hw4/main.cpp b/oop_hw3/hw4/main.cpp new file mode 100644 index 0000000..a24076b --- /dev/null +++ b/oop_hw3/hw4/main.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +class A { +public: + A() { + data = -1; + } + A(int n) :data(n) { + + } + int& Data(){ + return data; + } +private: + int data; +}; + +auto g = [](int n) { + A* p = new A[n]; + for (int i = 0;i < n;i++) { + p[i].Data() = i + 1; + } + for (int i = n-1;i >= 0;i--) { + cout << p[i].Data() << " "; + } + cout << endl; +}; + +int main() { + int a; + cin >> a; + g(a); + return 0; +} \ No newline at end of file diff --git a/oop_hw3/hw4/测试截图4.png b/oop_hw3/hw4/测试截图4.png new file mode 100644 index 0000000..88e6651 Binary files /dev/null and b/oop_hw3/hw4/测试截图4.png differ diff --git a/oop_hw3/hw5/main.cpp b/oop_hw3/hw5/main.cpp new file mode 100644 index 0000000..c2ea698 --- /dev/null +++ b/oop_hw3/hw5/main.cpp @@ -0,0 +1,39 @@ +#include +#include +#include "vector.h" + +using namespace std; +int main() { + Vector test; + Vector stest; + int m, n; + cin >> m >> n; + test = Vector(m, n); + stest = Vector(m, n); + for (int i = 0;i < m;i++) { + for (int j = 0;j < n;j++) { + cin >> test[i][j]; + } + } + for (int i = 0;i < m;i++) { + for (int j = 0;j < n;j++) { + cin >> stest[i][j]; + } + } + test[0][0] = -1; + stest[0][0] = "Hello, world!"; + for (int i = 0;i < m;i++) { + for (int j = 0;j < n;j++) { + cout << setw(4) << test[i][j]; + } + cout << endl; + } + for (int i = 0;i < m;i++) { + for (int j = 0;j < n;j++) { + cout << setw(20) << right << stest[i][j]; + } + cout << endl; + } + + return 0; +} \ No newline at end of file diff --git a/oop_hw3/hw5/vector.h b/oop_hw3/hw5/vector.h new file mode 100644 index 0000000..ba6f789 --- /dev/null +++ b/oop_hw3/hw5/vector.h @@ -0,0 +1,81 @@ +#ifndef VECTOR_H +#define VECTOR_H +#include + +template +class Vector { +private: + T** p; + int hang; + int lie; +public: + Vector(); + Vector(int m, int n); + Vector& operator=(const Vector& x); + T* operator[](int x); + void AlterElement(int m, int n, T x); + ~Vector(); +}; + +template +Vector::Vector() { + p = nullptr; + hang = 0; + lie = 0; +} + +template +Vector::Vector(int m, int n) { + hang = m; + lie = n; + p = new T * [m]; + for (int i = 0;i < m;i++) { + p[i] = new T[n]; + } +} + +template +Vector::~Vector() { + if (p) { + for (int i = 0; i < hang; i++) { + delete[] p[i]; + } + delete[] p; + } +} + +template +Vector& Vector::operator=(const Vector& x) { + if (p) { + for (int i = 0; i < hang; i++) { + delete[] p[i]; + } + delete[] p; + } + hang = x.hang; + lie = x.lie; + p = new T * [hang]; + for (int i = 0; i < hang; i++) { + p[i] = new T[lie]; + for (int j = 0; j < lie; j++) { + p[i][j] = x.p[i][j]; + } + } + return *this; +} + +template +T* Vector::operator[](int x) +{ + return p[x]; +} + +template +inline void Vector::AlterElement(int m, int n, T x) +{ + p[m][n] = x; +} + + + +#endif // !VECTOR_H diff --git a/oop_hw4/03_面向对象程序设计上机实验三.docx b/oop_hw4/03_面向对象程序设计上机实验三.docx new file mode 100644 index 0000000..2e18f88 Binary files /dev/null and b/oop_hw4/03_面向对象程序设计上机实验三.docx differ diff --git a/oop_hw4/Q123.cpp b/oop_hw4/Q123.cpp new file mode 100644 index 0000000..f207f2a --- /dev/null +++ b/oop_hw4/Q123.cpp @@ -0,0 +1,57 @@ +#include +using std::string; +using std::cout; +using std::cin; + +class thief{ + private: + string name; + double money; + bool caught; + public: + thief(){ + name = ""; + money = -1; + caught = false; + } + thief(string n,double m,bool c){ + name = n; + money = m; + caught = c; + } + thief& steal(walker x){ + money = x.money_print(); + x.zero(); + return this; + } +}; + +class walker{ + private: + string name; + double money; + bool stolen; + public: + walker(){ + name = ""; + money = -1; + stolen = false; + } + walker(string n,double m,bool c){ + name = n; + money = m; + stolen = c; + } + double money_print(){ + return money; + } + walker& zero(){ + money = 0; + stolen = true; + return this; + } +}; + +class police{ + +}; diff --git a/oop_hw4/hw123/main.cpp b/oop_hw4/hw123/main.cpp new file mode 100644 index 0000000..2820d6e --- /dev/null +++ b/oop_hw4/hw123/main.cpp @@ -0,0 +1,29 @@ +#include +#include "thief.h" +#include "walker.h" +#include "police.h" + +using std::string; +using std::cout; +using std::cin; +using std::endl; + +int main() { + thief t1("Dan", 100, false), t2("Trevor", 50.4, false), t3("Mike", 30.2, false); + walker w1("Man", 1000, false), w2("Wan", 5000, false); + t1.steal(w1); + t2.steal(w2); + t1.display(); + t2.display(); + w1.display(); + w2.display(); + police p1("Officer", 0, 0), p2("Reciffo", 1, 1), p3("fw", 0, 0); + p1.caught(t1); + p2.caught(t2); + cout << "After Caught" << endl; + p1.display(); + p2.display(); + t1.display(); + t2.display(); + return 0; +} \ No newline at end of file diff --git a/oop_hw4/hw123/police.cpp b/oop_hw4/hw123/police.cpp new file mode 100644 index 0000000..87adbd8 --- /dev/null +++ b/oop_hw4/hw123/police.cpp @@ -0,0 +1,28 @@ +#include +#include "walker.h" +#include "police.h" +#include "thief.h" +using std::string; +using std::cout; +using std::cin; +using std::endl; + +police::police(){ + name = ""; + money = -1; + respect = -1; +} +police::police(string n, double m, int r) { + name = n ; + money = m ; + respect = r ; +} +police& police::caught(thief& x) { + money += 100; + respect++; + x.becaught(); + return *this; +} +void police::display() { + cout << name << " " << money << " " << "Respect :" << respect << endl; +} \ No newline at end of file diff --git a/oop_hw4/hw123/police.h b/oop_hw4/hw123/police.h new file mode 100644 index 0000000..521edad --- /dev/null +++ b/oop_hw4/hw123/police.h @@ -0,0 +1,22 @@ +#pragma once +#include +#include "thief.h" +#include "walker.h" + +class thief; + +using std::string; +using std::cout; +using std::cin; + +class police { +private: + string name; + double money; + int respect; +public: + police(); + police(string n, double m, int r); + police& caught(thief& x); + void display(); +}; \ No newline at end of file diff --git a/oop_hw4/hw123/thief.cpp b/oop_hw4/hw123/thief.cpp new file mode 100644 index 0000000..8625184 --- /dev/null +++ b/oop_hw4/hw123/thief.cpp @@ -0,0 +1,33 @@ +#include +#include "thief.h" +#include "walker.h" +#include "police.h" +using std::string; +using std::cout; +using std::cin; +using std::endl; + +thief::thief() { + name = ""; + money = -1; + caught = false; + } +thief::thief(string n, double m, bool c = false) { + name = n; + money = m; + caught = c; + } +thief& thief::steal(walker& x) { + money += x.money_print(); + x.zero(); + caught = true; + return *this; +} +thief& thief::becaught() { + money = 0; + caught = false; + return *this; +} +void thief::display() { + cout << name << " " << money << " " << "If caught :" << caught << endl; +} diff --git a/oop_hw4/hw123/thief.h b/oop_hw4/hw123/thief.h new file mode 100644 index 0000000..7363141 --- /dev/null +++ b/oop_hw4/hw123/thief.h @@ -0,0 +1,24 @@ +#pragma once +#include +#include "walker.h" +#include "police.h" + +class walker; + +using std::string; +using std::cout; +using std::cin; + +class thief { +private: + string name; + double money; + bool caught; +public: + thief(); + thief(string n, double m, bool c); + thief& steal(walker& x); + void display(); + thief& becaught(); + +}; \ No newline at end of file diff --git a/oop_hw4/hw123/walker.cpp b/oop_hw4/hw123/walker.cpp new file mode 100644 index 0000000..66a5153 --- /dev/null +++ b/oop_hw4/hw123/walker.cpp @@ -0,0 +1,32 @@ +#include +#include "thief.h" +#include "walker.h" +#include "police.h" + + +using std::string; +using std::cout; +using std::cin; +using std::endl; + +walker::walker() { + name = ""; + money = -1; + stolen = false; + } +walker::walker(string n, double m, bool c = false) { + name = n; + money = m; + stolen = c; + } + double walker::money_print() { + return money; + } +walker& walker::zero() { + money = 0; + stolen = true; + return *this; + } +void walker::display() { + cout << name << " " << money << " " << "If stolen :" << stolen << endl; +} \ No newline at end of file diff --git a/oop_hw4/hw123/walker.h b/oop_hw4/hw123/walker.h new file mode 100644 index 0000000..173b68f --- /dev/null +++ b/oop_hw4/hw123/walker.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include "thief.h" +#include "police.h" + +using std::string; +using std::cout; +using std::cin; + +class walker { +private: + string name; + double money; + bool stolen; +public: + walker(); + walker(string n, double m, bool c); + double money_print(); + walker& zero(); + void display(); +}; \ No newline at end of file diff --git a/oop_hw4/hw123/测试截图123.png b/oop_hw4/hw123/测试截图123.png new file mode 100644 index 0000000..4eae7f3 Binary files /dev/null and b/oop_hw4/hw123/测试截图123.png differ diff --git a/oop_hw4/hw4/main.cpp b/oop_hw4/hw4/main.cpp new file mode 100644 index 0000000..4591157 --- /dev/null +++ b/oop_hw4/hw4/main.cpp @@ -0,0 +1,33 @@ +#include +#include +#include "man.h" +#include "woman.h" + +using std::string; +using std::cout; +using std::cin; +using std::endl; + + +int main() { + man m1("Zhang", false , NULL), m2("Wang", false , NULL), m3("Li", true , NULL), m4("Zhao", true , NULL); + woman w1("Wan", false, NULL), w2("Wu", false, NULL), w3("Xu", true, NULL), w4("Zhou", true, NULL); + m1.marry(&w1); + m2.marry(&w2); + m3.marry(&w3); + m4.marry(&w4); + cout << "Set" << endl; + m1.show() == NULL ? cout << "Devorced" << endl : cout << m1.show()->display() << endl; + m2.show() == NULL ? cout << "Devorced" << endl : cout << m2.show()->display() << endl; + m3.show() == NULL ? cout << "Devorced" << endl : cout << m3.show()->display() << endl; + m4.show() == NULL ? cout << "Devorced" << endl : cout << m4.show()->display() << endl; + cout << "Arrange" << endl; + m2.devorce(&w2); + m4.devorce(&w4); + m1.show() == NULL ? cout << "Devorced" << endl : cout << m1.show()->display() << endl; + m2.show() == NULL ? cout << "Devorced" << endl : cout << m2.show()->display() << endl; + m3.show() == NULL ? cout << "Devorced" << endl : cout << m3.show()->display() << endl; + m4.show() == NULL ? cout << "Devorced" << endl : cout << m4.show()->display() << endl; + + return 0; +} \ No newline at end of file diff --git a/oop_hw4/hw4/man.cpp b/oop_hw4/hw4/man.cpp new file mode 100644 index 0000000..0acaa37 --- /dev/null +++ b/oop_hw4/hw4/man.cpp @@ -0,0 +1,33 @@ +#include +#include "woman.h" +#include "man.h" + +using std::string; +using std::cout; +using std::cin; +using std::endl; + + man::man() { + name = ""; + married = false; + w = NULL; + } + man::man(string n, bool m, woman* x) { + name = n; + married = m; + w = x; + } + void man::marry(woman* x) { + w = x; + married = true; + } + void man::devorce(woman* x) { + w = NULL; + married = false; + } + string man::display() { + return name; + } + woman* man::show() { + return w; + } diff --git a/oop_hw4/hw4/man.h b/oop_hw4/hw4/man.h new file mode 100644 index 0000000..0428788 --- /dev/null +++ b/oop_hw4/hw4/man.h @@ -0,0 +1,24 @@ +#pragma once +#include +#include "woman.h" + +using std::string; +using std::cout; +using std::cin; +using std::endl; + +class woman; + +class man { +private: + string name; + bool married; + woman* w; +public: + man(); + man(string n, bool m, woman* x); + void marry(woman* x); + void devorce(woman* x); + string display(); + woman* show(); +}; \ No newline at end of file diff --git a/oop_hw4/hw4/woman.cpp b/oop_hw4/hw4/woman.cpp new file mode 100644 index 0000000..9f81d88 --- /dev/null +++ b/oop_hw4/hw4/woman.cpp @@ -0,0 +1,34 @@ +#include +#include "man.h" +#include "woman.h" + +using std::string; +using std::cout; +using std::cin; +using std::endl; + + + woman::woman() { + name = ""; + married = false; + w = NULL; + } + woman::woman(string n, bool m, man* x) { + name = n; + married = m; + w = x; + } + void woman::marry(man* x) { + w = x; + married = true; + } + void woman::devorce(man* x) { + w = NULL; + married = false; + } + string woman::display() { + return name; + } + man* woman::show() { + return w; + } diff --git a/oop_hw4/hw4/woman.h b/oop_hw4/hw4/woman.h new file mode 100644 index 0000000..883fd3e --- /dev/null +++ b/oop_hw4/hw4/woman.h @@ -0,0 +1,24 @@ +#pragma once +#include +#include "man.h" + +using std::string; +using std::cout; +using std::cin; +using std::endl; + +class man; + +class woman { +private: + string name; + bool married; + man* w; +public: + woman(); + woman(string n, bool m, man* x); + void marry(man* x); + void devorce(man* x); + string display(); + man* show(); +}; \ No newline at end of file diff --git a/oop_hw4/hw4/测试截图4.png b/oop_hw4/hw4/测试截图4.png new file mode 100644 index 0000000..964b157 Binary files /dev/null and b/oop_hw4/hw4/测试截图4.png differ diff --git a/oop_hw4/hw6/main.cpp b/oop_hw4/hw6/main.cpp new file mode 100644 index 0000000..a630305 --- /dev/null +++ b/oop_hw4/hw6/main.cpp @@ -0,0 +1,76 @@ +#include +#include + +class A { +private: + int data[10]; // ģڲ + + // ̬Աͳ + static size_t createdCount; + static size_t destroyedCount; + static size_t totalAllocatedBytes; + static size_t currentUsedBytes; + +public: + // new + void* operator new(size_t size) { + createdCount++; + totalAllocatedBytes += size; + currentUsedBytes += size; + std::cout << "[new] size = " << size << std::endl; + return ::operator new(size); + } + + // delete + void operator delete(void* ptr, size_t size) { + destroyedCount++; + currentUsedBytes -= size; + std::cout << "[delete] size = " << size << std::endl; + ::operator delete(ptr); + } + + // new[] + void* operator new[](size_t size) { + // ڿܺ󣬼 + createdCount++; // ע⣺ֻͳһΣɸϸͳ + totalAllocatedBytes += size; + currentUsedBytes += size; + std::cout << "[new[]] size = " << size << std::endl; + return ::operator new[](size); + } + + // delete[] + void operator delete[](void* ptr, size_t size) { + destroyedCount++; // ͬ + currentUsedBytes -= size; + std::cout << "[delete[]] size = " << size << std::endl; + ::operator delete[](ptr); + } + + // ͳϢ + static void showStats() { + std::cout << "Created: " << createdCount << std::endl; + std::cout << "Destroyed: " << destroyedCount << std::endl; + std::cout << "Total allocated: " << totalAllocatedBytes << " bytes" << std::endl; + std::cout << "Current in use: " << currentUsedBytes << " bytes" << std::endl; + } +}; + +// ̬Աʼ +size_t A::createdCount = 0; +size_t A::destroyedCount = 0; +size_t A::totalAllocatedBytes = 0; +size_t A::currentUsedBytes = 0; + +int main() { + A* a1 = new A; + A* a2 = new A; + delete a1; + + A* arr = new A[3]; + delete[] arr; + + A::showStats(); + return 0; +} + diff --git a/oop_hw4/hw7/aws.txt b/oop_hw4/hw7/aws.txt new file mode 100644 index 0000000..6b9eeeb --- /dev/null +++ b/oop_hw4/hw7/aws.txt @@ -0,0 +1,12 @@ +一、为什么重载 + 一般用自由函数形式? + 原因:+ 具有交换律,左操作数不一定是你定义的类对象。自由函数可以让任意顺序都合法,因为左右参数都可以指定类型。 + + +二、为什么重载 += 一般用成员函数形式? + 原因:a += b 本质是修改 a(左操作数),必须能访问并修改其内部状态。自由函数虽然也能写,但不能直接访问私有成员,需要提供 setter 或 friend,不优雅。 + + 三、为什么重载 = 必须是成员函数? +原因:a = b 是赋值,修改的是左操作数的内部状态,必须有 this 指针。C++ 强制 operator= 只能是成员函数(标准规定)。 + +四、为什么重载 << 要用自由函数? +原因:std::cout << obj 左操作数是 std::ostream,你没法修改它的定义。如果不用自由函数就会变成 trip << cout,不符合逻辑 \ No newline at end of file diff --git a/oop_hw4/hw8/main.cpp b/oop_hw4/hw8/main.cpp new file mode 100644 index 0000000..49272ac --- /dev/null +++ b/oop_hw4/hw8/main.cpp @@ -0,0 +1,23 @@ +#include +#include "page.h" +using std::cin; +using std::cout; +using std::endl; + +int main() { + Paginate pager(13); + for (int i = 1;i <= 13;i++) + { + //iǰҳ13ҳ + pager.setPage(i).show(); + } + cout << "START MOVING...." << endl; + pager.setPage(5).show(); + pager.next().show(); + pager.prev().show(); + //ֱӷ5ҳ + pager.nextN().show(); + pager.next().show(); + pager.prevN().show(); + return 0; +} \ No newline at end of file diff --git a/oop_hw4/hw8/page.cpp b/oop_hw4/hw8/page.cpp new file mode 100644 index 0000000..a4a061e --- /dev/null +++ b/oop_hw4/hw8/page.cpp @@ -0,0 +1,87 @@ +#include +#include "page.h" + +using std::cin; +using std::cout; +using std::endl; + +void out(int n) { + switch (n) + { + case 1: + cout << "ҳ 1+ 2 3 4 5 13 ҳ" << endl; + break; + case 2: + cout << "ҳ 1 2+ 3 4 5 13 ҳ" << endl; + break; + case 3: + cout << "ҳ 1 2 3+ 4 5 13 ҳ" << endl; + break; + case 4: + cout << "ҳ 1 2 3 4+ 5 13 ҳ" << endl; + break; + case 5: + cout << "ҳ 1 2 3 4 5+ 13 ҳ" << endl; + break; + case 6: + cout << "ҳ 1 6+ 7 8 9 10 13 ҳ" << endl; + break; + case 7: + cout << "ҳ 1 6 7+ 8 9 10 13 ҳ" << endl; + break; + case 8: + cout << "ҳ 1 6 7 8+ 9 10 13 ҳ" << endl; + break; + case 9: + cout << "ҳ 1 6 7 8 9+ 10 13 ҳ" << endl; + break; + case 10: + cout << "ҳ 1 6 7 8 9 10+ 13 ҳ" << endl; + break; + case 11: + cout << "ҳ 1 9 10 11+ 12 13 ҳ" << endl; + break; + case 12: + cout << "ҳ 1 9 10 11 12+ 13 ҳ" << endl; + break; + case 13: + cout << "ҳ 1 9 10 11 12 13+ ҳ" << endl; + break; + default: + cout << "Fail!" << endl; + break; + } +} + + + +Paginate::Paginate() { + page_now = 0; + page_total = 0; +} +Paginate::Paginate(int n) { + page_total = n; +} +Paginate& Paginate::setPage(int n) { + page_now = n; + return *this; +} +Paginate& Paginate::next() { + page_now += 1; + return *this; +} +Paginate& Paginate::prev() { + page_now -= 1; + return *this; +} +Paginate& Paginate::nextN() { + page_now += 5; + return *this; +} +Paginate& Paginate::prevN() { + page_now -= 5; + return *this; +} +void Paginate::show() { + out(this->page_now); +} diff --git a/oop_hw4/hw8/page.h b/oop_hw4/hw8/page.h new file mode 100644 index 0000000..3dfb678 --- /dev/null +++ b/oop_hw4/hw8/page.h @@ -0,0 +1,20 @@ +#pragma once +#include +using std::cin; +using std::cout; +using std::endl; + +class Paginate { +private: + int page_total; + int page_now; +public: + Paginate(); + Paginate(int n); + Paginate& setPage(int n); + void show(); + Paginate& next(); + Paginate& prev(); + Paginate& nextN(); + Paginate& prevN(); +}; \ No newline at end of file diff --git a/oop_hw4/hw8/测试截图8.png b/oop_hw4/hw8/测试截图8.png new file mode 100644 index 0000000..dbcf1d2 Binary files /dev/null and b/oop_hw4/hw8/测试截图8.png differ diff --git a/oop_hw4/上机测试4 (1).pdf b/oop_hw4/上机测试4 (1).pdf new file mode 100644 index 0000000..cf3039d Binary files /dev/null and b/oop_hw4/上机测试4 (1).pdf differ diff --git a/oop_hw5/04_面向对象程序设计上机实验四_参考答案.docx b/oop_hw5/04_面向对象程序设计上机实验四_参考答案.docx new file mode 100644 index 0000000..fdd2cad Binary files /dev/null and b/oop_hw5/04_面向对象程序设计上机实验四_参考答案.docx differ diff --git a/oop_hw5/hw1/ans.md b/oop_hw5/hw1/ans.md new file mode 100644 index 0000000..79eeb0f --- /dev/null +++ b/oop_hw5/hw1/ans.md @@ -0,0 +1,152 @@ +## **1)第一段代码分析:递归构造与输出** + +```cpp +class A { +public: + A(int n):val(n){} +protected: + int val; +}; + +class B : public A { +public: + B(int n) :A(n) + { + pB = (n > 0 ? new B(n-1) : 0); + } + + ~B() { delete pB; } + + void Display() + { + cout << val << endl; + if (pB != 0) + pB->Display(); + } + +private: + B* pB; +}; +``` + +### 📌 构造逻辑: + +* `B(4)` 被创建时,会递归构造 `B(3) → B(2) → B(1) → B(0) → B(-1)` 停止(因 `n == 0` 时 `pB = 0`) +* 每一层的 `val` 都是当前 `n` + +### 📌 输出逻辑: + +`b.Display()` 调用后会: + +```cpp +cout << 4 + -> Display() on B(3) + cout << 3 + -> Display() on B(2) + cout << 2 + -> Display() on B(1) + cout << 1 + -> Display() on B(0) + cout << 0 +``` + +所以最终输出是: + +``` +4 +3 +2 +1 +0 +``` + +### ✅ **运行结果1**: + +``` +4 +3 +2 +1 +0 +``` + +--- + +## **2)第二段代码分析:构造顺序与拷贝构造** + +```cpp +class A { +public: + A(int n):num(n) { Out(); } + A(const A& rhs):num(rhs.num) { Out(); } + void Out() { cout << num << endl; } +private: + int num; +}; + +class B : public A { +public: + B(A& a) : obj(a), A(1) { } + void Out() { obj.Out(); } + +private: + A obj; +}; +``` + +### 📌 构造顺序注意: + +在 `B(A& a) : obj(a), A(1)` 中,尽管初始化顺序写的是先 `obj`,再 `A`,**但实际构造顺序是:** + +1. 先构造基类 A(即 `A(1)`) +2. 再构造成员对象 `obj(a)`(调用拷贝构造函数) + +### 📌 main 函数: + +```cpp +A a(8); // 输出:8 +B b1(a); // 顺序: + // A(1) → 输出:1 + // obj(a) 拷贝构造 → 输出:8 +B b2(b1); // 和上面类似,只是复制的是 b1 对象的成员 obj + // A(1) → 输出:1 + // obj(b1.obj) 拷贝构造 → 输出:8 + +b2.Out(); // 调用 obj.Out() → 输出:8 +``` + +### ✅ **运行结果2**: + +``` +8 +1 +8 +1 +8 +8 +``` + +--- + +## ✅ 两段程序的输出分别是: + +### **程序1 输出:** + +``` +4 +3 +2 +1 +0 +``` + +### **程序2 输出:** + +``` +8 +1 +8 +1 +8 +8 +``` diff --git a/oop_hw5/hw2/animal.cpp b/oop_hw5/hw2/animal.cpp new file mode 100644 index 0000000..ae3d99b --- /dev/null +++ b/oop_hw5/hw2/animal.cpp @@ -0,0 +1,57 @@ +#include "animal.h" +#include +#include + +Animal::Animal() { + name = "#UNDEFINED"; + weight = -1; +} +Animal::Animal(std::string n, int w) { + name = n; + weight = w; +} +std::string Animal::show_name() +{ + return name; +} +int Animal::show_weight() +{ + return weight; +} +void Animal::who() { + std::cout << "This is an Animal" << std::endl; + std::cout << "Name : " << name << std::endl + << "Weight : " << weight << std::endl; +} +Lion::Lion() { + this->change_name("#UNDEFINED_LION_NAME"); + this->change_weight(-1); +} +Lion::Lion(std::string n,int w) { + this->change_name(n); + this->change_weight(w); +} +void Lion::who() { + std::cout << "This is a Lion" << std::endl; + std::cout << "Name : " << this->show_name() << std::endl + << "Weight : " << this->show_weight() << std::endl; +} +Aardvark::Aardvark() { + this->change_name("#UNDEFINED_LION_NAME"); + this->change_weight(-1); +} +Aardvark::Aardvark(std::string n, int w) { + this->change_name(n); + this->change_weight(w); +} +void Aardvark::who() { + std::cout << "This is a Aardvark" << std::endl; + std::cout << "Name : " << this->show_name() << std::endl + << "Weight : " << this->show_weight() << std::endl; +} +void Animal::change_name(std::string cn) { + name = cn; +} +void Animal::change_weight(int cw) { + weight = cw; +} \ No newline at end of file diff --git a/oop_hw5/hw2/animal.h b/oop_hw5/hw2/animal.h new file mode 100644 index 0000000..739e996 --- /dev/null +++ b/oop_hw5/hw2/animal.h @@ -0,0 +1,34 @@ + +#pragma once +#include +#include + +class Animal { +private: + std::string name; + int weight; +public: + Animal(); + Animal(std::string n, int w); + std::string show_name(); + int show_weight(); + void change_name(std::string cn); + void change_weight(int cw); + virtual void who(); +protected: + +}; + +class Lion : public Animal { +public: + Lion(); + Lion(std::string n, int w); + void who(); +}; + +class Aardvark : public Animal { +public: + Aardvark(); + Aardvark(std::string n, int w); + void who(); +}; \ No newline at end of file diff --git a/oop_hw5/hw2/main.cpp b/oop_hw5/hw2/main.cpp new file mode 100644 index 0000000..5cb745b --- /dev/null +++ b/oop_hw5/hw2/main.cpp @@ -0,0 +1,17 @@ +#include +#include +#include "animal.h" + +using std::cout; +using std::cin; +using std::endl; + +int main() { + Animal a("Animal!", 100); + Lion b("Lion W", 200); + Aardvark c("Aardvark", 300); + a.who(); + b.who(); + c.who(); + return 0; +} \ No newline at end of file diff --git a/oop_hw5/hw2/测试截图2.png b/oop_hw5/hw2/测试截图2.png new file mode 100644 index 0000000..4fb14df Binary files /dev/null and b/oop_hw5/hw2/测试截图2.png differ diff --git a/oop_hw5/hw3/main.cpp b/oop_hw5/hw3/main.cpp new file mode 100644 index 0000000..aea17ec --- /dev/null +++ b/oop_hw5/hw3/main.cpp @@ -0,0 +1,22 @@ +#include +#include "person.h" + +using std::cout; +using std::endl; +using std::string; + +int main() { + Employee a[5]; + Executive b[5]; + a[0] = Employee(20, "Zhang", 1, 1001); + a[1] = Employee(21, "Wang", 1, 1002); + a[2] = Employee(19, "Zhao", 0, 1003); + a[3] = Employee(22, "Li", 1, 1004); + a[4] = Employee(28, "Zh", 0, 1145); + a[0].display(); + a[1].display(); + a[2].display(); + a[3].display(); + a[4].display(); + return 0; +} \ No newline at end of file diff --git a/oop_hw5/hw3/person.cpp b/oop_hw5/hw3/person.cpp new file mode 100644 index 0000000..fa2e136 --- /dev/null +++ b/oop_hw5/hw3/person.cpp @@ -0,0 +1,72 @@ +#include "person.h" + +Person::Person(int a, string n, bool g) +{ + age = a; + name = n; + gender = g; +} + +void Person::change_age(int ca) +{ + age = ca; +} + +void Person::change_name(string cn) +{ + name = cn; +} + +void Person::change_gender(bool x) +{ + gender = x; +} + +int Person::show_age() +{ + return age; +} + +string Person::show_name() +{ + return name; +} + +bool Person::show_gender() +{ + return gender; +} + +void Person::display() +{ + cout << "This is a Person" << endl + << "Name : " << name << endl + << "Age : " << age << endl + << "Gender : "; + gender == false ? cout << "Woman" << endl : cout << "Man" << endl; +} + +void Employee::add_number(int n) +{ + number = n; +} + +void Employee::display() +{ + cout << "This is an Employee" << endl + << "Name : " << this->show_name() << endl + << "Age : " << this->show_age() << endl + << "Gender : "; + this->show_gender() == false ? cout << "Woman" << endl : cout << "Man" << endl; + cout << "Number ID : " << number << endl; +} + +void Executive::display() +{ + cout << "This is an Executive" << endl + << "Name : " << this->show_name() << endl + << "Age : " << this->show_age() << endl + << "Gender : "; + this->show_gender() == false ? cout << "Woman" << endl : cout << "Man" << endl; + //cout << "Number ID : " << number << endl; +} diff --git a/oop_hw5/hw3/person.h b/oop_hw5/hw3/person.h new file mode 100644 index 0000000..6faded4 --- /dev/null +++ b/oop_hw5/hw3/person.h @@ -0,0 +1,41 @@ +#pragma once +#include +#include + +using std::cout; +using std::cin; +using std::endl; +using std::string; + +class Person { +private: + int age; + string name; + //enum string gender = { "Male","Female" }; Բôд + bool gender;//1 = Male , 0 = Female +public: + Person() :age(-1), name("#UNDEFINED"), gender(true) {}; + Person(int a, string n, bool g); + void change_age(int ca); + void change_name(string cn); + void change_gender(bool x); + int show_age(); + string show_name(); + bool show_gender(); + virtual void display(); +}; + +class Employee : public Person { +private: + int number; +public: + Employee() :Person(-1, "#UNDEFINED", true), number(-1) {}; + Employee(int a, string n, bool g, int num) : Person(a, n, g), number(num) {}; + void add_number(int n); + void display(); +}; +class Executive : public Employee { +public: + void display(); +}; + diff --git a/oop_hw5/hw3/测试截图3.png b/oop_hw5/hw3/测试截图3.png new file mode 100644 index 0000000..834442a Binary files /dev/null and b/oop_hw5/hw3/测试截图3.png differ diff --git a/oop_hw5/hw4/code/ab.h b/oop_hw5/hw4/code/ab.h new file mode 100644 index 0000000..b3d233b --- /dev/null +++ b/oop_hw5/hw4/code/ab.h @@ -0,0 +1,51 @@ +#pragma once +#include +#include + +using std::cin; +using std::cout; +using std::endl; + +class A +{ +public: + A(int num) :data1(num) {} + ~A() { + cout << " Destory A" << endl; + } + void f() const { + cout << " Excute A::f() "; + cout << " Data1=" << data1 << endl; + } + void g() + { + cout << " Excute A::g() " << endl; + } +protected: + int data1; +}; + +class B : public A +{ +public: + B(int num1, int num2) :A(num1), data2(num2) {} + ~B() { + cout << " Destory B" << endl; + } + void f() const { + cout << " Excute B::f() "; + cout << " Data1=" << data1; + cout << " Data2=" << data2 << endl; + } + void f(int n) const { + cout << " Excute B::f(int) "; + cout << " n=" << n; + cout << " Data1=" << data1; + cout << " Data2=" << data2 << endl; + } + void h() { + cout << " Excute B::h() " << endl; + } +private: + int data2; +}; \ No newline at end of file diff --git a/oop_hw5/hw4/code/main.cpp b/oop_hw5/hw4/code/main.cpp new file mode 100644 index 0000000..706116d --- /dev/null +++ b/oop_hw5/hw4/code/main.cpp @@ -0,0 +1,72 @@ +#pragma once +#include +#include + +using std::cin; +using std::cout; +using std::endl; + +class A +{ +public: + A(int num) :data1(num) {} + virtual ~A() { + cout << " Destory A" << endl; + } + void f() const { + cout << " Excute A::f() "; + cout << " Data1=" << data1 << endl; + } + void g() + { + cout << " Excute A::g() " << endl; + } + A& operator=(A& x) { + data1 = x.data1; + return *this; + } +protected: + int data1; +}; + +class B : public A +{ +public: + B(int num1, int num2) :A(num1), data2(num2) {} + virtual ~B() { + cout << " Destory B" << endl; + } + void f() const { + cout << " Excute B::f() "; + cout << " Data1=" << data1; + cout << " Data2=" << data2 << endl; + } + void f(int n) const { + cout << " Excute B::f(int) "; + cout << " n=" << n; + cout << " Data1=" << data1; + cout << " Data2=" << data2 << endl; + } + void h() { + cout << " Excute B::h() " << endl; + } + B& operator=(B& x) { + data2 = x.data2; + //data1 = x.data1; + this->A::operator=(x); + return *this; + } +private: + int data2; +}; + +int main() { + B b(1, 2); + A* p = new B(1, 2); + b.f(); + b.g(); + b.f(3); + b.h(); + delete p; + return 0; +} \ No newline at end of file diff --git a/oop_hw5/hw4/测试截图4.png b/oop_hw5/hw4/测试截图4.png new file mode 100644 index 0000000..0f97476 Binary files /dev/null and b/oop_hw5/hw4/测试截图4.png differ diff --git a/oop_hw5/hw4/题目以及答案文字部分.md b/oop_hw5/hw4/题目以及答案文字部分.md new file mode 100644 index 0000000..d8ef9e4 --- /dev/null +++ b/oop_hw5/hw4/题目以及答案文字部分.md @@ -0,0 +1,345 @@ + +## 4.阅读代码,并按要求练习。 +``` cpp +class A +{ +public: + A(int num):data1(num) {} + ~A(){ + cout<<" Destory A"<A::operator=(other); + //这种写法也可以 + data2 = other.data2; + } + return *this; + } +}; +``` + + +--- +- ##### 7)分别创建 A 和 B 类的两个对象 a 和 b,分别执行 a.f(),b.f(),a.g(),b.g(),a.f(1),b.f(1),a.h(),b.h(),请问哪些可以通过编译,执行结果如何? +✅ 调用: + +```cpp +A a(1); +B b(2, 3); +a.f(); // ✅ A::f() +b.f(); // ✅ B::f() +a.g(); // ✅ A::g() +b.g(); // ✅ A::g() 继承而来 +a.f(1); // ❌ 无此函数 +b.f(1); // ✅ B::f(int) +a.h(); // ❌ 无此函数 +b.h(); // ✅ B::h() +``` + +--- +- ##### 8)增加代码 A * p=new B(1,2);,理解向上类型转换的安全性。 +✅已完成: +```cpp +A* p = new B(1, 2); +``` + +✅ 安全,称为“向上转型”(upcasting),**B 是 A 的子类**。安全的主要原因: +“向上类型转换的安全性”是面向对象编程中一个很关键但也容易被忽略的点,尤其在 C++ 中。 + +--- + +## ✅ 什么是向上类型转换(Upcasting)? + +向上类型转换:**将派生类对象的指针或引用转换为基类类型的指针或引用**。 + +比如: + +```cpp +class A { }; +class B : public A { }; + +B b; +A* pa = &b; // 向上类型转换(Upcasting) +``` + +--- + +## ✅ 安全性的本质 + +### ✅ **向上转换是安全的、隐式允许的** + +因为: + +* 每个派生类对象**本质上包含一个完整的基类子对象部分**。 +* 所以把 `B*` 转为 `A*` 是有意义的:`A` 的部分总是存在的。 + +> 换句话说,你永远可以“安全地把一个更具体的对象视为一个更抽象的对象”。 + +--- + +## ✅ 示例 + +```cpp +class A { +public: + void foo() { cout << "A::foo\n"; } +}; + +class B : public A { +public: + void bar() { cout << "B::bar\n"; } +}; + +int main() { + B b; + A* pa = &b; // 向上转换,安全 + + pa->foo(); // ✅合法,调用 A 的函数 + // pa->bar(); // ❌错误:A 类型中没有 bar() +} +``` + +--- + +## ❗ 注意事项:类型“退化” + +向上转换后: + +* **只能访问基类中的成员**,即便实际指向的是一个派生类对象; +* 若函数是非虚函数,则会“静态绑定”到基类版本; +* 若函数是虚函数,则会“动态绑定”到派生类重写版本(见多态); + +--- + +## ✅ 与向下转换对比 + +| 类型转换方式 | 安全性 | 是否隐式 | 风险 | +| --------- | ----- | ---- | ---------------- | +| 向上转换(B→A) | ✅ 安全 | ✅ 是 | 无 | +| 向下转换(A→B) | ❌ 不安全 | ❌ 否 | 若对象本非 B 类型,结果未定义 | + + + +--- +- ##### 9)在 8)的基础上,执行 p->f(),输出是什么?与 B* p=new B(1,2); p->f();的结果一样吗? +✅执行后: + +默认情况下(`f()` 非虚函数): + +```cpp +p->f(); // 输出 A::f() +``` + +若你希望执行的是 `B::f()`,**应将 A 的 `f()` 声明为 `virtual`**。 + +--- +- ##### 10)在 8)的基础上,执行 p->f(1),能通过编译吗?为什么? +✅编译? + +```cpp +p->f(1); // ❌ 报错:A 类中无 f(int) +``` + +即使实际对象是 B,编译器只看指针类型(A),而 A 没有 `f(int)`。 + +--- +- ##### 11)在 8)的基础上,执行 p->g()和 p->h(),能行吗?为什么? +✅编译? + +```cpp +p->f(1); // ❌ 报错:A 类中无 f(int) +``` + +即使实际对象是 B,编译器只看指针类型(A),而 A 没有 `f(int)`。 + +--- +- ##### 12)在 8)的基础上,执行 delete p;,输出是什么?B 类的析构函数执行了吗? +✅输出: + +如果 `A` 的析构函数不是 `virtual`,那么: + +```cpp +delete p; // 只会调用 A 的析构函数,❌ 不会调用 B 的析构函数 +``` + +输出: + +``` +Destory A +``` + +⚠️ 此时会发生**资源泄漏**,因为 `B` 中资源未释放! + +✅ 正确写法是: + +```cpp +class A { +public: + virtual ~A() { + cout << "Destory A" << endl; + } + // ... +}; +``` + +这样 `delete p;` 才会调用 B 的析构函数 → 输出顺序: + +``` +Destory B +Destory A +``` + +--- + +## ✅ 总结重点 + +| 问题 | 核心知识 | +| ---- | -------------------------- | +| 2–3 | 访问权限(private vs protected) | +| 4–5 | 继承方式(public/private)影响成员访问 | +| 6 | 拷贝构造函数 & 赋值操作符 | +| 7–11 | 多态、向上转型、成员函数隐藏 | +| 12 | 虚析构函数,资源释放 | + +--- + diff --git a/oop_hw5/hw5/main.cpp b/oop_hw5/hw5/main.cpp new file mode 100644 index 0000000..d1cfbc5 --- /dev/null +++ b/oop_hw5/hw5/main.cpp @@ -0,0 +1,128 @@ +#include +using namespace std; + +class A { +public: + A(int num) : data(num) { + cout << "A constructed with data = " << data << endl; + } + void AFuncs() { + cout << "This is A's public function!" << endl; + } + A(const A& other) : data(other.data) { + cout << "A copy constructor called." << endl; + } + A& operator=(const A& other) { + if (this != &other) { + data = other.data; + } + return *this; + } + ~A() { + cout << "A destructor called." << endl; + } + +protected: + int data; +}; + +class B { +public: + B(int num) : value(num) { + cout << "B constructed with value = " << value << endl; + } + void BFuncs() { + cout << "This is B's public function!" << endl; + } + B(const B& other) : value(other.value) { + cout << "B copy constructor called." << endl; + } + B& operator=(const B& other) { + if (this != &other) { + value = other.value; + } + return *this; + } + ~B() { + cout << "B destructor called." << endl; + } + +protected: + int value; +}; + +// === ԭʼ̳а汾 === +class C1 : public A, private B { +public: + C1(int num1, int num2, int y) : A(num1), B(num2), yyy(y) { + cout << "C1 constructed with yyy = " << yyy << endl; + } + void MyFuncs() { + BFuncs(); + cout << "This function calls B::BFuncs() !" << endl; + } + +private: + int yyy; +}; + +// === ̳ + ϰ汾 === +class C2 : public A { +public: + C2(int num1, int num2, int y) + : A(num1), b(num2), yyy(y) { + cout << "C2 constructed with yyy = " << yyy << endl; + } + + C2(const C2& other) + : A(other), b(other.b), yyy(other.yyy) { + cout << "C2 copy constructor called." << endl; + } + + C2& operator=(const C2& other) { + if (this != &other) { + A::operator=(other); + b = other.b; + yyy = other.yyy; + } + cout << "C2 assignment operator called." << endl; + return *this; + } + + ~C2() { + cout << "C2 destructor called." << endl; + } + + void MyFuncs() { + b.BFuncs(); + cout << "This function calls B::BFuncs() !" << endl; + } + +private: + B b; + int yyy; +}; + +// === === +int main() { + cout << "=== ̳в ===" << endl; + C1 obj1(10, 20, 30); + obj1.AFuncs(); + obj1.MyFuncs(); + cout << endl; + + cout << "=== ̳ + ϲ ===" << endl; + C2 obj2(100, 200, 300); + obj2.AFuncs(); + obj2.MyFuncs(); + + cout << "--- ---" << endl; + C2 obj3 = obj2; + + cout << "--- ֵ ---" << endl; + C2 obj4(1, 2, 3); + obj4 = obj3; + + cout << "--- ˳ʼ ---" << endl; + return 0; +} diff --git a/oop_hw5/hw5/测试截图5.png b/oop_hw5/hw5/测试截图5.png new file mode 100644 index 0000000..f68bf93 Binary files /dev/null and b/oop_hw5/hw5/测试截图5.png differ diff --git a/oop_hw5/hw6/main.cpp b/oop_hw5/hw6/main.cpp new file mode 100644 index 0000000..f5a0e0a --- /dev/null +++ b/oop_hw5/hw6/main.cpp @@ -0,0 +1,131 @@ +#include +#include + +using std::cout; +using std::endl; +using std::string; + +class Wall +{ +public: + Wall() :color(0) + { + cout << "һǽ" << endl; + } + void Paint(int newColor) + { + color = newColor; + cout << "ɫˢǽ" << endl; + } + int GetColor() const + { + return color; + } + virtual void display() { + cout << "עɫɫ012345678" << endl; + cout << "Wall Color ? : " << this->GetColor() << endl; + + } + virtual ~Wall() { + cout << "Wall" << endl; + } +private: + int color; +}; +class Door +{ +public: + Door() :openOrClose(false) + { + cout << "һ" << endl; + } + void Open() + { + if (!IsOpened()) + { + openOrClose = true; + cout << "ű" << endl; + } + else + { + cout << "ſأ" << endl; + } + } + void Close() + { + if (IsOpened()) + { + openOrClose = false; + cout << "ű" << endl; + } + else + { + cout << "Źأ" << endl; + } + } + bool IsOpened() const + { + return openOrClose; + } + virtual ~Door() { + + } +private: + bool openOrClose; +}; +//ɫɫ012345678 +class WallWithDoor : public Wall, public Door{ +public: + WallWithDoor() : Door(), Wall(){} + WallWithDoor(bool fl,int cl) { + this->Paint(cl); + fl == true ? this->Open() : this->Close(); + if (cl == 1) this->Close(); + if (cl == 4) this->Open(); + } + void display() { + cout << "עɫɫ012345678" << endl; + cout << "Door is Open? :" << this->IsOpened() << endl; + cout << "Wall Color ? : " << this->GetColor() << endl; + } +}; + +class WallWithDoor_Combined { +private: + Door x; + Wall y; +public: + WallWithDoor_Combined() : x(), y() {} + WallWithDoor_Combined(bool fl, int cl) { + y.Paint(cl); + fl == true ? x.Open() : x.Close(); + if (cl == 1) x.Close(); + if (cl == 4) x.Open(); + } + void display() { + cout << "עɫɫ012345678" << endl; + cout << "Door is Open? :" << x.IsOpened() << endl; + cout << "Wall Color ? : " << y.GetColor() << endl; + } +}; + +int main() { + WallWithDoor a1(true,1); + WallWithDoor a2(true, 2); + WallWithDoor a3(true, 4); + WallWithDoor_Combined b1(true,1); + WallWithDoor_Combined b2(true, 2); + WallWithDoor_Combined b3(true, 4); + Wall* p = new Wall(); + Wall* t1 = &a1; //ת + WallWithDoor* t2 = dynamic_cast (p);//ת + cout << typeid(t2).name() << endl; + p->display(); + a1.display(); + a2.display(); + a3.display(); + b1.display(); + b2.display(); + b3.display(); + return 0; +} \ No newline at end of file diff --git a/oop_hw5/hw6/测试截图6.png b/oop_hw5/hw6/测试截图6.png new file mode 100644 index 0000000..48cfdaa Binary files /dev/null and b/oop_hw5/hw6/测试截图6.png differ diff --git a/oop_hw5/上机测试5 (1).pdf b/oop_hw5/上机测试5 (1).pdf new file mode 100644 index 0000000..886ae6e Binary files /dev/null and b/oop_hw5/上机测试5 (1).pdf differ diff --git a/oop_hw6/05_面向对象程序设计上机实验五.docx b/oop_hw6/05_面向对象程序设计上机实验五.docx new file mode 100644 index 0000000..209237b Binary files /dev/null and b/oop_hw6/05_面向对象程序设计上机实验五.docx differ diff --git a/oop_hw6/hw1/QA1.md b/oop_hw6/hw1/QA1.md new file mode 100644 index 0000000..8750f2c --- /dev/null +++ b/oop_hw6/hw1/QA1.md @@ -0,0 +1,156 @@ + + +### **1)去掉(1)中的 `virtual`,比较执行结果。** + +```cpp +virtual ~A() {...} +``` + +如果去掉 `virtual`,在通过 `A* p = new B;` 创建对象并用 `delete p;` 释放时: + +* **原代码**:会先调用 `B::~B()`,再调用 `A::~A()`(因为析构函数是虚函数,发生动态绑定,析构顺序正确)。 +* **去掉 `virtual` 后**:只会调用 `A::~A()`,不会调用 `B::~B()`,**可能导致子类资源未释放,产生内存泄漏或行为异常**。 + +✅ **结论**:基类应将析构函数设为 `virtual`,以确保通过基类指针删除时能调用子类析构函数。 + +--- + +### **2)去掉(6)中的 `const`,可以吗?** + +```cpp +virtual int Func1() const; +``` + +不可以。因为你在基类 A 中定义的是: + +```cpp +virtual int Func1() const = 0; +``` + +这是一个**纯虚函数**,要求派生类重写时函数签名必须完全一致。如果你去掉 `const`,则签名不同,**不会重写该函数**,导致类 `B` 仍然是抽象类,不能实例化。 + +--- + +### **3)(3) 和 (7) 中各自定义了参数的缺省值,(12) 执行时匹配的是哪个缺省值?为什么?** + +```cpp +// A 类中: +virtual void Func2(int = 500) = 0; + +// B 类中: +virtual void Func2(int = 1000) +``` + +语句 `(12)` 是: + +```cpp +p->Func2(); // 没传参数 +``` + +此时 `p` 是 `A*` 类型。**函数的缺省参数在编译时根据指针静态类型决定**,所以用的是 `A::Func2(int=500)` 中的默认值。 + +✅ **结论**: + +* 缺省参数值是静态绑定的,跟对象的动态类型无关。 +* 编译时看的是指针类型 `A*`,所以用了 `500` 而不是 `1000`。 + +--- + +### **4)(4) 中的 `protected` 改为 `private` 可以吗?** + +```cpp +protected: + static int lineno; +``` + +如果改为 `private`,**派生类 `B` 就不能访问 `lineno`,会导致编译错误**(如构造函数中 `++lineno`)。 + +✅ **结论**:基类希望子类访问成员变量,应使用 `protected`;`private` 不可被子类访问。 + +--- + +### **5)去掉 (5) 中的 `virtual`,对结果有影响吗?** + +```cpp +virtual ~B() { ... } +``` + +如果 `~A()` 是虚函数,那么即使 `~B()` 不是虚函数,也会通过动态绑定调用 `~B()`。 + +✅ **结论**:去掉 `virtual` 不影响结果(只要基类析构函数是虚函数),但建议保留以提高可读性和一致性。 + +--- + +### **6)(9) 的作用是什么?** + +```cpp +int A::lineno = 0; +``` + +这是静态成员变量 `lineno` 的定义和初始化,**必须在类外初始化**,否则会链接错误。 + +✅ **作用**:为类的所有对象共享一份 `lineno` 计数器,用来输出行号。 + +--- + +### **7)(10) 中改为 `A* p = new A;` 可以吗?** + +```cpp +A * p = new A; // 错误 +``` + +`A` 是抽象类(包含纯虚函数),**不能实例化**。会导致编译错误。 + +✅ **结论**:抽象类不能直接创建对象,只能用于指针或引用指向派生类。 + +--- + +### **8)去掉(3)中的 `virtual`,结果会有什么改变?** + +```cpp +void Func2(int = 500) = 0; // 去掉 virtual -> 变成普通纯函数? +``` + +这在语义上是错误的。**纯虚函数必须是虚函数**,否则语法不合法。 + +✅ **结论**:不能去掉,纯虚函数必须是 `virtual`。 + +--- + +### **9)(14) 为什么不对?将 (8) 改为 `virtual` 后,(14) 可以了吗?** + +```cpp +// (14) p->Func3(100); +``` + +`p` 是 `A*`,而 `Func3()` 并未在 `A` 中声明,因此不能通过 `A*` 调用,即使 `Func3()` 是 `virtual`。 + +✅ **结论**: + +* 静态类型决定能否调用某函数。 +* 即使改成虚函数,也需要 `A` 中声明它,才能通过 `A*` 调用。 + +--- + +### **10)(15) 为什么不对?理解编译时静态类型和运行时动态类型的含义。** + +```cpp +// p->Func1(100); // 错误 +``` + +在 `B` 中有两个重载版本: + +```cpp +int Func1(int n) const; +int Func1() const; +``` + +但 `A* p` 只能看到 `A::Func1() const` 版本(无参数)。你尝试调用的是 `Func1(int)`,这在 `A` 中根本没有定义,编译时报错。 + +✅ **结论**: + +* 编译时由静态类型决定调用哪个函数(是否存在该函数签名)。 +* 运行时由动态类型决定调用哪个版本(多态行为)。 +* 所以 `p->Func1(100)` 不合法,因为 `A` 中没这个函数签名。 + + diff --git a/oop_hw6/hw2&3/main.cpp b/oop_hw6/hw2&3/main.cpp new file mode 100644 index 0000000..1a0e659 --- /dev/null +++ b/oop_hw6/hw2&3/main.cpp @@ -0,0 +1,9 @@ +#include +#include "monster.h" +using namespace std; +int main(){ + Wolf A(100, 10, 3); + Snake B(50, 15, 5); + Monster::fight(A,B); + return 0; +} \ No newline at end of file diff --git a/oop_hw6/hw2&3/monster.cpp b/oop_hw6/hw2&3/monster.cpp new file mode 100644 index 0000000..1160220 --- /dev/null +++ b/oop_hw6/hw2&3/monster.cpp @@ -0,0 +1,59 @@ +#include "monster.h" +#include +#include +#include + + +std::string demangle(const char* name) { + std::string s = name; + std::string prefix = "class "; + if (s.find(prefix) == 0) { + s = s.substr(prefix.length()); + } + return s; +} + +void Monster::fight(Monster& a, Monster& b) +{ + //aȹb + while (a.hp > 0 && b.hp > 0) { + a.attack(b); + if (a.hp <= 0) break; + b.attack(a); + } + //дһtypeid() + std::string x, y; + x = demangle(typeid(a).name()); + y = demangle(typeid(b).name()); + a.hp > 0 ? std::cout << "Monster " << x << " wins" << std::endl : std::cout << "Monster "<< y << " wins" << std::endl; +} + +double& Monster::show_hp() +{ + return this->hp; +} + +double& Monster::show_damage() +{ + return this->damage; +} + +double& Monster::show_defence() +{ + return this->defence; +} + +void Wolf::attack(Monster& a) +{ + a.show_hp() -= this->show_damage() - a.show_defence(); + std::cout << "Attacked! (!Wolf) remains " << a.show_hp() << " HP" << std::endl; +} + +void Snake::attack(Monster& a) +{ + a.show_hp() -= this->show_damage() - a.show_defence(); + std::cout << "Attacked! (!Snake) remains " << a.show_hp() << " HP" << std::endl; +} +Monster::~Monster() { + +} \ No newline at end of file diff --git a/oop_hw6/hw2&3/monster.h b/oop_hw6/hw2&3/monster.h new file mode 100644 index 0000000..4d8c075 --- /dev/null +++ b/oop_hw6/hw2&3/monster.h @@ -0,0 +1,34 @@ +#pragma once +#include + +class Monster { +private: + double hp; + double damage; + double defence; +public: + Monster() : hp(0), damage(0), defence(0) {}; + Monster(double h, double dam, double den) : hp(h), damage(dam), defence(den) {}; + virtual void attack(Monster& a) = 0; + static void fight(Monster& a,Monster& b); + double& show_hp(); + double& show_damage(); + double& show_defence(); + virtual ~Monster(); +}; + +class Wolf : public Monster{ +public: + Wolf() : Monster(0,0,0){}; + Wolf(double h, double dam, double den) : Monster(h, dam, den) {}; + void attack(Monster& a) override; + +}; + +class Snake : public Monster { +public: + Snake() : Monster(0, 0, 0) {}; + Snake(double h, double dam, double den) : Monster(h, dam, den) {}; + void attack(Monster& a) override; + +}; \ No newline at end of file diff --git a/oop_hw6/hw2&3/测试截图2.png b/oop_hw6/hw2&3/测试截图2.png new file mode 100644 index 0000000..1f0d68b Binary files /dev/null and b/oop_hw6/hw2&3/测试截图2.png differ diff --git a/oop_hw6/hw4/box.cpp b/oop_hw6/hw4/box.cpp new file mode 100644 index 0000000..8deab99 --- /dev/null +++ b/oop_hw6/hw4/box.cpp @@ -0,0 +1,70 @@ +#include "box.h" +#include +#include +#include + +std::string demangle(const std::string name) { + std::string s = name; + std::string prefix = "class "; + if (s.find(prefix) == 0) { + s = s.substr(prefix.length()); + } + return s; +} + +Box& Box::inBox(Fruit& x) +{ + fruit[num] = &x /*static_cast ()*/; + num++; + return *this; + // TODO: ڴ˴ return +} + +int Box::numApple() +{ + int numA = 0; + for (int i = 0;i < num;i++) { + //std::string x = typeid(fruit[i]).name(); + //std::cout << demangle(x) << std::endl; + Fruit* tmp = (Fruit*)fruit[i]; + if (tmp->checkLoss() == 4) numA++; + } + return numA; +} +int Box::numOrange() +{ + int numA = 0; + for (int i = 0;i < num;i++) { + Fruit* tmp = (Fruit*)fruit[i]; + if (tmp->checkLoss() == 3) numA++; + } + return numA; +} + +int Box::WeightLoss() +{ + int WS = 0; + for (int i = 0;i < num;i++) { + if ( ((Fruit*)fruit[i])->isDryed() == false) { + WS += ((Fruit*)fruit[i])->checkLoss(); + } + } + return WS; +} + +int Box::totalWeight() +{ + int TotalW = 0; + for (int i = 0;i < num;i++) { + TotalW += ((Fruit*)fruit[i])->checkWeight(); + } + return TotalW; +} + +void Box::UPDATE_ALL() +{ + for (int i = 0;i < num;i++) { + ((Fruit*)fruit[i])->upDate(); + } +} + diff --git a/oop_hw6/hw4/box.h b/oop_hw6/hw4/box.h new file mode 100644 index 0000000..bcded49 --- /dev/null +++ b/oop_hw6/hw4/box.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include "fruit.h" + + +class Box { +private: + void* fruit[8]{}; + int num = 0; + int TotalDate = 0; + int lossTotal = 0; +public: + int returnDate(); + Box& inBox(Fruit& x); + int numApple(); + int numOrange(); + int WeightLoss(); + int totalWeight(); + void UPDATE_ALL(); + friend Fruit; +}; \ No newline at end of file diff --git a/oop_hw6/hw4/fruit.cpp b/oop_hw6/hw4/fruit.cpp new file mode 100644 index 0000000..e31e79b --- /dev/null +++ b/oop_hw6/hw4/fruit.cpp @@ -0,0 +1,60 @@ +#include "fruit.h" + +Fruit::Fruit() +{ + weight = 0; + loss = 0; +} + +Fruit::Fruit(int w, int l) +{ + weight = w; + loss = l; +} + +int& Fruit::checkWeight() +{ + return weight; +} + +int Fruit::checkLoss() +{ + return loss; +} + +void Fruit::upDate() +{ + this->DatePassed++; +} + +void Fruit::Dryed() +{ + this->Dry = true; +} + +bool Fruit::isDryed() +{ + return Dry; +} + +void Apple::losewater() +{ + if (this->checkWeight() > 30) { + this->checkWeight() -= 4; + } + else + { + this->Dryed(); + } +} + +void Orange::losewater() +{ + if (this->checkWeight() > 18) { + this->checkWeight() -= 3; + } + else + { + this->Dryed(); + } +} diff --git a/oop_hw6/hw4/fruit.h b/oop_hw6/hw4/fruit.h new file mode 100644 index 0000000..f600698 --- /dev/null +++ b/oop_hw6/hw4/fruit.h @@ -0,0 +1,39 @@ +#pragma once +#include + +class Fruit { +private: + int weight; + int loss; + int DatePassed = 0; + bool Dry = false; +public: + Fruit(); + Fruit(int w, int l); + int& checkWeight(); + int checkLoss(); + void upDate(); + void Dryed(); + bool isDryed(); + virtual void losewater() = 0; +}; + +class Apple : public Fruit { +private: + +public: + Apple() : Fruit(50, 4) {}; + //Apple(int, int) = delete; + Apple(const Apple& x) = delete; + void losewater(); +}; + +class Orange : public Fruit { +private: + +public: + Orange() : Fruit(30, 3) {}; + //Orange(int, int) = delete; + Orange(const Apple& x) = delete; + void losewater(); +}; \ No newline at end of file diff --git a/oop_hw6/hw4/main.cpp b/oop_hw6/hw4/main.cpp new file mode 100644 index 0000000..f4ff306 --- /dev/null +++ b/oop_hw6/hw4/main.cpp @@ -0,0 +1,56 @@ +#include +#include "box.h" +#include "fruit.h" + +using namespace std; +int main() { + Apple A[8]; + Orange O[8]; + Box B; + cout << "Day 1" << endl; + B.inBox(A[0]); + B.inBox(O[0]); + cout << "Apple : " << B.numApple() << endl; + cout << "Orange : " << B.numOrange() << endl; + cout << "WeightLoss : " << B.WeightLoss() << endl; + B.UPDATE_ALL(); + + cout << "Day 2" << endl; + B.inBox(A[1]); + B.inBox(O[1]); + cout << "Apple : " << B.numApple() << endl; + cout << "Orange : " << B.numOrange() << endl; + cout << "WeightLoss : " << B.WeightLoss() << endl; + cout << "Total Weight : " << B.totalWeight() << endl; + B.UPDATE_ALL(); + + cout << "Day 3" << endl; + B.inBox(A[2]); + cout << "Apple : " << B.numApple() << endl; + cout << "Orange : " << B.numOrange() << endl; + cout << "WeightLoss : " << B.WeightLoss() << endl; + cout << "Total Weight : " << B.totalWeight() << endl; + + B.UPDATE_ALL(); + + cout << "Day 4" << endl; + B.inBox(O[2]); + cout << "Apple : " << B.numApple() << endl; + cout << "Orange : " << B.numOrange() << endl; + cout << "WeightLoss : " << B.WeightLoss() << endl; + cout << "Total Weight : " << B.totalWeight() << endl; + + B.UPDATE_ALL(); + + cout << "Day 5" << endl; + B.inBox(A[3]); + B.inBox(O[3]); + cout << "Apple : " << B.numApple() << endl; + cout << "Orange : " << B.numOrange() << endl; + cout << "WeightLoss : " << B.WeightLoss() << endl; + cout << "Total Weight : " << B.totalWeight() << endl; + + B.UPDATE_ALL(); + + return 0; +} \ No newline at end of file diff --git a/oop_hw6/hw4/测试截图4.png b/oop_hw6/hw4/测试截图4.png new file mode 100644 index 0000000..e530dbb Binary files /dev/null and b/oop_hw6/hw4/测试截图4.png differ diff --git a/oop_hw6/hw5/main.cpp b/oop_hw6/hw5/main.cpp new file mode 100644 index 0000000..3b49303 --- /dev/null +++ b/oop_hw6/hw5/main.cpp @@ -0,0 +1,86 @@ +#include +using namespace std; +class CallBackObject; +class Server +{ +public: + Server(int size) :len(size) + { + data = new int [len];//1 + for (int i = 0;i < len;++i) + data[i] = i + 1; + } + ~Server() { delete[] data; }//2 + int Total(CallBackObject& obj); +private: + int len; + int* data; +}; + +class CallBackObject +{ +public: + virtual ~CallBackObject() {} + virtual int CallBackFunc(int val) = 0;//4 +}; + +class ClientA :public CallBackObject +{ +public: + virtual ~ClientA() {} + virtual int CallBackFunc(int val) + { + return val; + } + void RequestA(Server& srv) + { + cout << srv.Total(*this) << endl;//5 + } +}; +int Server::Total(CallBackObject& obj) +{ + int sum = 0; + for (int i = 0; i < len; ++i) { + sum += obj.CallBackFunc(data[i]);//3 + } + return sum; +} + +class ClientB :public CallBackObject +{ +public: + virtual ~ClientB() {} + virtual int CallBackFunc(int val) + { + return val * val;//6 + } + void RequestB(Server& srv) { + cout << "ƽ=" << srv.Total(*this) << endl;//7 + } +}; + +//1 +int main() +{ + Server srv2(2), srv5(5); + ClientA a; + a.RequestA(srv2); //3 + a.RequestA(srv5); //15 +//2 + Server ssrv3(3); + ClientB b; + b.RequestB(srv2); + b.RequestB(srv3); + return 0; +} + +/* +1)ֱո1 - 5ȷĴ룬ʹ1Ϊ315. +2)ֱո6 - 7ȷĴ룬ʹ2Ϊ +ƽ = 5 +ƽ = 14 +3)ʵClientBеغʹ2Ϊ +1 2 = 9 +1 2 3 = 36 + +*/ \ No newline at end of file diff --git a/oop_hw6/hw5/测试截图5.png b/oop_hw6/hw5/测试截图5.png new file mode 100644 index 0000000..661675c Binary files /dev/null and b/oop_hw6/hw5/测试截图5.png differ diff --git a/oop_hw6/上机测试6.pdf b/oop_hw6/上机测试6.pdf new file mode 100644 index 0000000..959679e Binary files /dev/null and b/oop_hw6/上机测试6.pdf differ