Created
July 19, 2012 16:26
-
-
Save aybabtme/3145102 to your computer and use it in GitHub Desktop.
Learning C++ : classes/headers. Doesn't work, and I don't get why.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "BagOfValues.h" | |
BagOfValues::BagOfValues() { | |
mName = "Jake"; | |
mWeight = 71.8; | |
mAge = 26; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef GUARD_BagOfValues_h | |
#define GUARD_BagOfValues_h | |
#include <string> | |
class BagOfValues { | |
public : | |
BagOfValues(); | |
std::string getName() { return mName; } | |
double getWeight() { return mWeight; } | |
int getAge() { return mAge; } | |
private : | |
std::string mName; | |
double mWeight; | |
int mAge; | |
}; | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# THIS IS WRONG | |
$ clang++ Test.cpp | |
/tmp/Test-c7XlKn.o:Test.cpp:function main: error: undefined reference to 'BagOfValues::BagOfValues()' | |
clang: error: linker command failed with exit code 1 (use -v to see invocation) | |
# / THIS IS WRONG | |
# THIS IS RIGHT | |
$ clang++ -c Test.cpp | |
$ clang++ -c BagOfValues.cpp | |
$ clang++ Test.o BagOfValues.o | |
$ ./a.out | |
My name is Jake | |
My age is 26 | |
My weight is 71.8 | |
# / THIS IS RIGHT |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "BagOfValues.h" | |
#include <iostream> | |
#include <string> | |
using std::cout; | |
using std::endl; | |
int main(){ | |
BagOfValues *aBag = new BagOfValues; | |
cout << "Your name is " << aBag->getName() << endl; | |
cout << "Your age is " << aBag->getAge() << endl; | |
cout << "Your weight is " << aBag->getWeight() << endl; | |
return 0; | |
} |
Got it! The code was just fine, the problem was in the linking.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using this code, I get a compile error. I don't get why, and I think I just don't understand how the header files work with the classes.