2015-10-17 80 views
1

我有一個關於測試用戶定義頭文件的問題。 所以,這裏是例子。測試用戶定義頭文件和其他問題

#include <iostream> 
using namesapce std; 

#include "header.h" 
#include "header.h" // I wonder the reason why I need to write this down two time for testing ifndef test. 

int main() 
{ 
    cout << "Hello World!" << endl; 
    cin.get(); 
} 

我知道我需要在driver.cpp中記下兩次用戶定義的頭文件名。但是,我不明白爲什麼我需要這樣做。

而且,這是第二個問題。

#include <iostream> 
#include <fstream> 
using namesapce std; 

int main() 
{ 
    fstream fin; 
    fin.open("info.txt"); 

    if(!fin.good()) throw "I/O Error\n"; // I want to know what throw exactly do. 
    else cout << "Hello World!\n"; 

    cin.get(); 
} 

所以,我的問題是扔功能。 我意識到,如果我使用throw而不是cout,我的編譯器將被終止。 我想知道什麼投擲確切做。

由於我是新來的人,我可能在格式和一些規則方面犯了一些錯誤,所以請隨時指出它們,如果我做到了。

謝謝!

回答

0

你的第一個問題,想象下面的例子:

MyHelper.cpp

int sum(int first , int second) 
{ 
    return first + second; 
} 

TEST.CPP

#include<iostream> 
#include"MyHelper.cpp" 
#include"MyHelper.cpp" 

int main() 
{ 
    std::cout << sum(2,4) << std::endl; 
} 

現在你也知道預編譯器取代了線的#include「MyHelper。 cpp「與相應文件的內容。

// here comes the code from iostream header 
// ... 
int sum(int first , int second) 
{ 
    return first + second; 
} 
int sum(int first , int second) 
{ 
    return first + second; 
} 

int main() 
{ 
    std::cout << sum(2,4) << std::endl; 
} 

這是編譯器收到的代碼。正如你看到符號總和現在被定義了多次。因此,編譯器將用相同的錯誤而退出:

t.c: In function ‘int sum(int, int)’: 
t.c:7:9: error: redefinition of ‘int sum(int, int)’ 
    int sum(int first , int second) 
     ^
t.c:3:9: note: ‘int sum(int, int)’ previously defined here 
    int sum(int first , int second) 
     ^

換句話說,如果有事情和includeguard是錯誤的,那麼編譯器將這個錯誤報告給你。

第二個問題:

throws用於拋出異常。我認爲有數以千計的例外教程。只需詢問您選擇的「C++異常教程」的搜索引擎並遵循其中的一個或兩個。就像下面的一個例子:

http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/

(滾動位下調至「更現實的例子:」如果你只是在用例感興趣)

+0

太謝謝你了! –