使用课程

时间:2012-07-03 04:50:58

标签: c++ class

所以我决定开始学习c ++我想知道如何在其中使用类。我以为我已经正确设置了(从查看教程)但它给了我以下错误..

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

我是c ++和Dev-C ++编译器的新手,所以我还没有弄清楚错误。 HEre是我的代码..

主要课程:

#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};      

};

任何帮助都会受到赞赏,我一直试图解决这个问题。

1 个答案:

答案 0 :(得分: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会为您编译并执行该程序。