Problem compiling C++ class
I am running a C++ program which uses a class from another .cpp file. The class only has a constructor. It works when I test it separately. The main program compiles,but when I run it, I have a bug in the constructor. Any one can think of any situation that c开发者_JS百科ould happen? Thanks.
I guess I just run the code in terminal, and it is fine. But when I try to build a project in eclipse, it shows following code has multiple definition error:
class model
{
public:
int textures [];
float vertices[][3];
float triangles[][13];
public:
model(const char*); // constructor
};
model::model(const char* filename)
{
error message is: multiple definition of `model::model(char const*)'
any idea?
You need to split your code into a .h (header) and a.cpp (implementation) file and put:
model::model(const char* filename)
{
in the latter. Or, rewrite your class so the definition of the constructor (and any other member functions) is inside the class in the header file:
class model {
...
model(const char*) {
// constructor body here
}
};
Anyway, I'll venture a random guess (given what you've posted, there little to go on). I'll guess that you've overflowed your triangle array (perhaps counter is too big) and you're trashing your heap or stack.
One more thing. This line:
if (str[0] != '#' and !str.empty())
is buggy. If str is empty, you don't want to be reading str[0]. You need to switch the order around:
if (!str.empty() and str[0] != '#')
The error happens because you get a new definition of the function every time your header is included somewhere. If it is is used in more than one place in the program, you get the error.
You probably want to define the constructor either in a separate implementation file (class goes to header so that others can use it, function implementations go to .cpp/cc files). Alternatively you can define it within the class block instead of doing it outside.
精彩评论