@sunrisepeak 谢谢。我已经理解了
g202080272
-
关于学习C++中的int main中new一个新的伐对象的困惑 -
关于学习C++中的int main中new一个新的伐对象的困惑各位大神,你们好,我是刚刚接触代码的新人,这是我关于在C++学习过程中遇到的一点小的疑惑
我利用AI出了一道题目以便于我的学习和知识掌握情况。
尽管我利用百度和AI的解答,我始终不是很明白为什么要会有这一行代码 EBook digital_book = new EBook("A Brief History of Time", 2048);*
题目内容是:你的任务是编写一个完整的C++程序,包含两个类和一个main函数,来模拟图书的入库和销毁过程。
以下是我的代码```
code_text
#include <iostream>
#include <string>// --- 基类 ---
class Book {
public:
std::string title;
Book(std::string n) : title(n) {
std::cout << "Book: " << title << " has been published." << std::endl;
}
~Book() {
std::cout << "Book: " << title << " has been archived." << std::endl;
}
};// --- 派生类 ---
class EBook : public Book {
public:
int* file_size_kb;
// 构造函数修正
EBook(std::string n, int size) : Book(n) {
file_size_kb = new int(size);
std::cout << "EBook: " << title << " has been digitized." << std::endl;
}
~EBook() {
std::cout << "EBook: " << title << "'s digital file has been erased." << std::endl;
delete file_size_kb;
}
};// --- main函数修正 ---
int main() {
std::cout << "--- Library Opening ---" << std::endl;
Book paper_book("The Lord of the Rings");
EBook* digital_book = new EBook("A Brief History of Time", 2048);
std::cout << "--- Library is operating ---" << std::endl;
delete digital_book;
std::cout << "--- Library Closing ---" << std::endl;
return 0;
}