2015-10-17 88 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

太谢谢你了! –