首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ Date 類多構造函數語法錯誤修正與最佳實踐

     編輯:程式設計綜合問答

原代碼錯誤點


Date::Date(); // 錯誤:定義時多了分號,視為聲明而非定義
{ month=1; day=1; year=2005; }

構造函數定義不應有分號,正確寫法:


Date::Date() { // 無分號
    month=1; day=1; year=2005;
}

完整修正版代碼


#include <iostream>
#include <string>
using namespace std;

class Date {
public:
    Date(int m, int d, int y);
    Date(int m, int d);
    Date(int m);
    Date(); // 聲明
    void display() const; // 建議加 const
private:
    int month, day, year;
};

// 使用初始化列表(高效、必須用於 const/引用成員)
Date::Date(int m, int d, int y) : month(m), day(d), year(y) {}
Date::Date(int m, int d) : month(m), day(d), year(2005) {}
Date::Date(int m) : month(m), day(1), year(2005) {}
Date::Date() : month(1), day(1), year(2005) {} // 修正:去掉分號

void Date::display() const {
    cout << month << "/" << day << "/" << year << endl;
}

int main() {
    Date d1(10,13,2005), d2(12,30), d3(10), d4;
    d1.display(); d2.display(); d3.display(); d4.display();
    return 0;
}

核心知識點總結

  • 構造函數定義語法:類外定義時 `<返回類型> <類名>::<構造函數名>(參數) { ... }`,**無返回類型、無分號**。
  • 初始化列表:優先於函數體賦值,對 `const`、`reference`、無默認構造的成員**必須**使用。
  • 默認參數替代重載:現代 C++ 推薦 `Date(int m=1, int d=1, int y=2005)` 單一構造函數配合默認參數,減少代碼重複。
  • const 正確性:不修改成員的方法(如 `display`)應加 `const`。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved