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

蹲街弑〆低调 提交于 2019-11-27 08:08:17

问题


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

回答1:


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

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



回答2:


Not related to the problem you were having but consider making a couple minor changes:

  1. Pass the argument in a const reference. const because you do not plan on changing the value of the argument and reference so that you do not create any additional temporary objects.

  2. C++ has an initializer concept that is more efficient then using the assignment operator on member 'id' in the body of the constructor. The current version of the constructor will call member id's default constructor and then its assignment constructor. The initializer concept (i.e. 'id(s)') will just call one method the copy constructor.

    Foo::Foo(const string& s) : id(s)
    {
    }



来源:https://stackoverflow.com/questions/3656050/c-undefined-reference-to-foofoostdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!