C++ classes and headers
I've recently started getting into c++ but I'm having trouble creating and using classes, when I try to run my program I get a few errors.
This is my header file: MyClass.h
#include <iostream>
class MyClass
{
public:
MyClass();
void setVar(int k);
private:
int x;
};
------------------------------------------
this is the actual class: MyClass.cpp
#include "MyClass.h"
MyClass::MyClass(){}
void MyClass::setVar(int k)
{
x = k;
}
-------------------------------------------------
this is my program MyClassTest.cpp
#include "MyClass.h"
using namespace std;
int main()
{
MyClass c;
return 0;
}
When I run it I get a few errors, I'm running it on a solaris machine with the command g++ MyClassTest.cpp
Is there something wrong with my implementation of these classes or the header?
It looks like you're only compiling one of the source files. You have to compile MyClass.cpp too. (I'm not familiar with g++ syntax; Linux classes were long ago :))
Complementing the post above:
g++ MyClassTest.cpp MyClass.cpp -o executable_name
BTW, there is the über usefulness of using both -Wall and -ansi arguments. First gives you warnings that could make your code crash and stuff -- better to take then into account; second is to make the compiler check everything according to ANSI C++ standards. So:
g++ main.cpp class.cpp -o test -Wall -ansi
Way to go.
g++ MyClassTest.cpp MyClass.cpp -o executable_name
BTW, there is the über usefulness of using both -Wall and -ansi arguments. First gives you warnings that could make your code crash and stuff -- better to take then into account; second is to make the compiler check everything according to ANSI C++ standards. So:
g++ main.cpp class.cpp -o test -Wall -ansi
Way to go.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement