Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

c++ " undefined reference to 'Foo::Foo(std::string)' "

I'm not too familiar with c++ and how instantiating objects work, so this is probably a very simple thing to solve. When I compile with g++ I get the error " undefined reference to 'Foo::Foo(std::string)' ". I want to create an instance of the class Foo that has a string parameter in its constructor. Here is the code:

Foo.h

#include <string>
using namespace std;

class Foo
{
    public:
        Foo(string s);

    private:
        string id;
};

Foo.cpp

#include <string>
#include "Foo.h"
using namespace std;

Foo::Foo(string s)
{
    id = s;
}

main.cpp

#include <string>
#include "Foo.h"
using namespace std;

int main()
{
    Foo foo("bar");

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're probably not including Foo.cpp in your compile line. It should look something like this:

g++ main.cpp Foo.cpp -o testFoo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...