【问题标题】:Unresolved external symbol for the mentioned code in description描述中提到的代码的未解析外部符号
【发布时间】:2017-04-17 06:18:47
【问题描述】:
 #include <iostream>
class t1
{
public:
    ~t1();
    static t1& fun();
private:
     t1()
     { 
     }
};

t1& t1::fun()
{
    return t1();
}

int main()
{
    t1::fun();
    return 0;
}

我得到未解析的外部符号。请帮忙。错误如下

错误 2 错误 LNK2019: 函数“public: static class t1 & __cdecl t1::fun( void)" (?fun@t1@@SAAAV1@XZ) D:\LXI\LXIRef\RefDesign_V01.00\Software\Solution\TestWebServer\TestWebServer.obj TestWebServer
错误 3 error LNK1120: 1 unresolved externals D:\LXI\LXIRef\RefDesign_V01.00\Software\Solution\Debug\TestWebServer.exe 1 1 TestWebServer

【问题讨论】:

  • 发布有关构建错误的问题时,请包含构建过程的完整输出。完整且无需编辑。最好将输出作为文本简单地复制粘贴到问题正文中。
  • 关于您的问题的提示:您在哪里实现(定义)t1 构造函数和析构函数?
  • 对不起,我会编辑代码,编译并重新发布。
  • 最后,如果您使用t1::fun 函数返回的引用,您将有未定义的行为。在t1::fun 中创建一个临时 对象,该对象将立即不复存在。返回对它的引用是不正确的。
  • 抱歉浪费了专家的宝贵时间。它与析构函数定义一起使用。但我试图复制的其他一些代码的真正问题。感谢您的宝贵时间。

标签: c++ oop static


【解决方案1】:

给构造函数和析构函数定义。

#include <iostream>
class t1

{

public:

    ~t1() {} // <<<< defined here

    static t1& fun();

private:

    t1() {} // << defined here

};

t1& t1::fun()

{

    return t1();

}

int main()

{

    t1::fun();

    return 0;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-07
    • 2012-11-10
    • 1970-01-01
    • 2011-02-09
    • 2016-10-09
    相关资源
    最近更新 更多