-3

そこで、C++ の学習を開始することにしました。C++ でクラスを使用する方法を知りたかったのです。(チュートリアルを見て)正しく設定したと思いましたが、次のエラーが表示されます..

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

私は c++ と Dev-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);      
    }

}

そして、Math ヘッダー ファイル:

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

};

何か助けていただければ幸いです。私はしばらくの間、これを解決しようとしています。

4

1 に答える 1

2

多くのJava風の構文を使用しています。あなたが持っているべきものはこれです(テストされていません):

//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);
}

そして、2つのcppファイルをコンパイルします(gccの場合)

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

Dev C ++ IDEを使用しているようです。その場合、IDEはプログラムをコンパイルして実行します。

于 2012-07-03T04:58:17.920 に答える