2012-07-03 30 views
-3

所以我決定開始學習C++我想了解如何在其中使用類。我想我已經正確設置它(從看教程),但它給了我下面的錯誤..使用類

C:\Dev-Cpp\main.cpp `Math' does not name a type 

我是新來的C++和開發-C++編譯器,所以我還沒有想出錯誤然而。這裏是我的代碼..

主要類:

#include <cstdlib> 
#include <iostream> 

using namespace std; 

//variables 
int integer; 
Math math; 

int main() 
{ 
    math = new Math(); 


    integer = math.add(5,2); 

    cout << integer << endl; 


    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

這裏是我Math.cpp類:

#include <cstdlib> 
#include <iostream> 
#include "Math.h" 

using namespace std; 

public class Math { 

    public Math::Math() { 

    } 

    public int Math::add(int one, int two) { 
      return (one+two);  
    } 

} 

且算術頭文件:

public class Math { 
     public: 
       public Math(); 
       public int add(int one, int two) {one=0; two=0};  

}; 

任何幫助將不勝感激,我一直在努力工作一段時間了。

+1

你是否包含Math.h(在你的主類中)? –

+5

C++的語法與Java不同。這段代碼中有大量的語法錯誤。閱讀一本好的C++書籍,瞭解基本語法。你可以在這裏找到一個很好的書籍列表:http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Naveen

+0

是的,'算術數學=新數學();'不是正確的語法。 http://www.cplusplus.com/reference/std/new/operator%20new%5B%5D/ 另外:'integer = m.add(5,2);',我沒有看到一個標識符'm' –

回答

2

您正在使用很多Java-ish語法。你應該有就是這個(未經測試):

//main.cpp 

#include <cstdlib> 
#include <iostream> 
#include "Math.h" 
using namespace std; 

int main() 
{ 
    //No Math m = new Math(); 
    //Either Math *m = new Math(); and delete m (later on) or below: 
    Math m; //avoid global variables when possible. 
    int integer = m.add(5,2); //its m not math. 
    cout << integer << endl; 
    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

對於MATH.H

class Math { //no `public` 
public: 
    Math(); 
    int add(int, int); 
}; 

對於Math.cpp

#include <cstdlib> 
#include <iostream> //unnecessary includes.. 
#include "Math.h" 

using namespace std; 

Math::Math() { 

} 

int Math::add(int one, int two) { 
    return (one+two); 
} 

和編譯兩個cpp文件(在GCC的情況下, )

$ g++ main.cpp Math.cpp 
$ ./a.out 

看來你正在使用Dev C++ IDE,在這種情況下,IDE會爲您編譯和執行程序。

+0

非常感謝,幫助了我很多。 –