C++中如何将构造函数作为另一个构造函数的参数?
问题分析与修复方案
核心错误点
main函数临时对象创建语法错误:原代码中Date dd(14,7,1954)的写法非法,不能在初始化列表内声明变量,直接使用临时对象构造即可。Date::is_valid逻辑冗余:原三元表达式写法可以简化为更直观的范围判断。- 成员函数缺少
const限定:只读的getter函数未加const,无法在const对象上调用,不符合C++ const正确性规范。 - 参数传递未优化:
Book构造函数和operator<<中传递Date对象时未用const引用,存在不必要的拷贝开销。 - 未处理异常:
Date构造函数会抛出Invalid异常,若不捕获会导致程序直接终止。
修复后的完整代码
#include <bits/stdc++.h> using namespace std; class Date{ public: class Invalid{};// 用于抛出错误的异常类 Date(int d,int m,int y); Date() = default; // 只读getter添加const限定 int get_day() const {return day;}; int get_month() const {return month;}; int get_year() const {return year;}; private: int day{1}; int month{1}; int year{2024}; bool is_valid() const; // 同样添加const }; Date::Date(int d,int m,int y):day{d},month{m},year{y} { if(!is_valid()) throw Date::Invalid{}; } bool Date::is_valid() const{ // 简化逻辑,直接返回月份是否在合法范围内 return month >= 1 && month <= 12; } // 参数改为const引用,避免拷贝 ostream& operator << (ostream& os, const Date& d){ return os << d.get_day() << '-' << d.get_month() << '-' << d.get_year(); } class Book{ public: // 默认构造函数简化,copyright_date直接使用默认构造的Date Book():ISBN("xxx-xx-x"),title("title"),author("Aloy") {} // Date参数改为const引用 Book(string isbn,string t,string a,const Date& c):ISBN(isbn),title(t),author(a),copyright_date(c) {} // getter添加const限定 string get_ISBN() const { return ISBN; } string get_title() const { return title; } string get_author() const { return author; } Date get_copyright_date() const { return copyright_date; } // print_info改为const,仅读取数据 void print_info() const { cout << "Book title: " << title << "\nAuthor: " << author << "\nISBN: " << ISBN << "\nCopyright date: " << copyright_date << "\nStatus: " << ((is_checked_out)? "Checked out":"Available") << endl; } // setters保持不变 void set_ISBN(string i){ ISBN=i; } void set_title(string t){ title=t; } void set_author(string a){ author=a; } void set_copyright_date(Date d){ copyright_date=d; } void check_in(){ is_checked_out = false; } void check_out(){ is_checked_out = true; } void check() const { // 添加const限定 cout << (is_checked_out ? "Out" : "Available") << endl; } private: string ISBN; string title; string author; Date copyright_date; bool is_checked_out{false}; }; // operator==参数改为const引用 bool operator==(const Book& b1, const Book& b2){ return b1.get_ISBN() == b2.get_ISBN(); } int main() { try { // 修正临时对象创建方式,直接调用Date构造函数 Book book1{"233-725-C2","Shadow of Mordor","J.R.R.Tolkien", Date(14,7,1954)}; book1.print_info(); } catch (const Date::Invalid&) { cerr << "Invalid date entered!" << endl; return 1; } return 0; }
额外说明
- 给只读操作的成员函数添加
const限定是C++最佳实践,确保代码的const正确性。 - 使用
const引用传递参数能减少对象拷贝开销,提升程序性能。 - 添加异常捕获逻辑可让程序在遇到非法日期时优雅处理,避免直接崩溃。
内容的提问来源于stack exchange,提问作者Ssekyanzi Aloysious
相关产品推荐
相关产品推荐

