未解析的外部符号“public: class Foo __thiscall Bar::bu(char const *)”

Unresolved external symbol "public: class Foo __thiscall Bar::bu(char const *)"

提问人:Jcrack 提问时间:2/3/2012 最后编辑:R. Martinho FernandesJcrack 更新时间:2/3/2012 访问量:695

问:

这是我所拥有的。我正在尝试使用自定义构造函数在 Bar 中创建 Foo 的实例。当我尝试从 Bar 的构造函数调用构造函数时,我得到和未解析的外部。

class Foo
{
public:
    // The custom constructor I want to use.
    Foo(const char*);
};

class Bar
{
public:
    Bar();
    //The instance of Foo I want to use being declared.
    Foo bu(const char*);
};

int main(int argc, char* args[])
{
    return 0;
}

Bar::Bar()
{
    //Trying to call Foo bu's constructor.
    bu("dasf");
}

Foo::Foo(const char* iLoc)
{
}
C++ unresolved-external

评论

1赞 peterept 2/3/2012
该代码无效。当您添加成员变量时,当您想要使用自定义构造器时,您可以将其作为指针:Foo *bu;然后在构造函数中创建实例。
0赞 Axel 2/3/2012
这是一个链接器问题。我认为您发布的来源不足以解决您在这里的问题。所有内容是否都在同一个翻译单元(文件)中声明?然后我认为它应该起作用。如果没有,您应该编辑源代码,指示存储在哪个文件中的内容,并为完整的编译器和链接器命令行提供相应的输出(在这种情况下不应该那么多)。
0赞 Axel 2/3/2012
@peterept:我认为这是有效的,只是 Bar::bu 被声明为返回 Foo 而不是成员变量的方法。在 Bar::Bar() 中,bu 方法被调用,返回一个未使用的对象。没有多大意义,但应该有效。
0赞 Jcrack 2/3/2012
@Axel 它都在一个文件中。粘贴的示例是我用来获取错误的示例,仅此而已。我不明白为什么它不起作用
1赞 peterept 2/3/2012
对不起,我很快就读完了。您只是缺少 Foo bu(const char*) 函数的实现。它未在上面的示例中列出。您声明了它,但没有提供它的实现。如果你的意思是 bu 是一个对象,那么我上面说的是正确的。只需让 Foo *bu 成为成员并分配它。

答:

0赞 Jesse Good 2/3/2012 #1

这可能是你想要的:

class Foo
{
public:
    // The custom constructor I want to use.
    Foo(const char*);
};

class Bar
{
public:
    Bar();
   //The instance of Foo I want to use being declared.
   Foo bu; // Member of type Foo
};

int main(int argc, char* args[])
{
    return 0;
}

Bar::Bar() : bu("dasf") // Create instance of type Foo
{
}

Foo::Foo(const char* iLoc)
{
}

至于这个声明:这是一个成员函数的声明,名为 接受 a 并返回 .未解决的符号错误是因为你从未定义过函数,但你想要的不是函数的实例。Foo bu(const char*);buconst char*FoobuFoo

看到评论后的其他方法:

class Foo
{
public:
    // The custom constructor I want to use.
    Foo(const char*);
};

class Bar
{
public:
    Bar();
    ~Bar() { delete bu;} // Delete bu
   //The instance of Foo I want to use being declared.
   Foo *bu; // Member of type Foo
};

int main(int argc, char* args[])
{
    return 0;
}

Bar::Bar() : bu(new Foo("dasf")) // Create instance of type Foo
{
}

Foo::Foo(const char* iLoc)
{
}

你的代码还有很多其他问题,也许写一本关于C++的书,比如《C++入门》会是个好主意。