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

C++ 類設計錯誤分析:編譯通過但運行異常的常見原因

     編輯:程式設計綜合問答

問題代碼特徵

用戶提供了一段包含多個語法錯誤的 C++ 代碼,編譯器報告 fatal error C1004: unexpected end of file found。

核心錯誤原因

  1. 類定義缺少右大括號和分號:代碼中 class CFraction 定義未正確閉合
  2. 函數定義嵌套錯誤:input() 函數內部又定義了 simplify() 等函數(C++ 不支持嵌套函數定義)
  3. main 函數拼寫錯誤:int mian() 應為 int main()
  4. 頭文件重複包含/缺少護衛:可能導致重複定義

修正後的代碼結構

#include <iostream>
using namespace std;

class CFraction {
private:
    int nume, deno;
    
    // 內部輔助函數:最大公約數
    int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return a;
    }

public:
    CFraction(int nu = 0, int de = 1) : nume(nu), deno(de) {}
    
    void set(int nu = 0, int de = 1) { nume = nu; deno = de; }
    
    void input() {
        char c;
        cout << "請輸入數據(格式:nu/de): ";
        while (true) {
            cin >> nume >> c >> deno;
            if (c != '/') {
                cout << "格式錯誤!請重新輸入: ";
            } else break;
        }
        simplify(); // 輸入後自動約分
    }
    
    void simplify() {
        int g = gcd(abs(nume), abs(deno));
        nume /= g;
        deno /= g;
        if (deno < 0) { nume = -nume; deno = -deno; } // 保證分母為正
    }
    
    void amplify(int n) { // 放大 n 倍
        nume *= n;
        simplify();
    }
    
    void output(int style = 0) const {
        cout << nume << "/" << deno << endl;
    }
};

int main() {
    CFraction a(3,7), b(6,8), c(1,7);
    a.output();
    a.set(2,5);
    a.output();
    a.input();
    b.simplify();
    b.output();
    c.amplify(5);
    c.output();
    return 0;
}

關鍵修正點

  • 將所有成員函數定義移出類體(或用 inline),修復嵌套定義錯誤
  • 添加 gcd 私有方法實現約分邏輯
  • 修正 amplify 邏輯(原代碼調用 input 明顯錯誤)
  • 補全類定義結尾 }; 和 main 拼寫
  • 使用構造函數初始化列表,const 正確性

調試建議

遇到 unexpected end of file 時,優先檢查:大括號匹配、類/函數定義完整性、頭文件包含護衛。使用 IDE 的代碼格式化/縮進功能可快速發現結構問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved