小飞将 2019-10-03 23:48 采纳率: 66.7%
浏览 1178
已采纳

C++ 构造函数遇到“undefined reference to”一个静态数据成员的问题

如题:

#include <iostream>
#include <string>

class Employee {
private:
    static unsigned id;
public:
    Employee() { m_id = ++id;}
    Employee(const std::string &s) { m_id = ++id; m_name = s;}

    Employee(const Employee&) = delete;
    Employee &operator=(const Employee&) = delete;

    unsigned get_id() { return m_id;}
    std::string get_name() { return m_name;}
    static void init_id() { id = 0;}
private:
    unsigned m_id;
    std::string m_name;
};

int main() {
    Employee::init_id();
    Employee a("wu"), b("sun"), c("liu");
    std::cout << a.get_id() << " and " << a.get_name() << std::endl;
    std::cout << b.get_id() << " and " << b.get_name() << std::endl;
    std::cout << c.get_id() << " and " << c.get_name() << std::endl;
}

遇到error:
图片说明

这是什么原因呢?

  • 写回答

2条回答 默认 最新

  • threenewbee 2019-10-04 10:22
    关注

    通过编译:

    #include <iostream>
    #include <string>
    
    class Employee {
    private:
        static unsigned id;
    public:
        Employee() { m_id = id++;}
        Employee(const std::string &s) { m_id = ++id; m_name = s;}
    
        Employee(const Employee&) {} //这里是c++14的写法,我编译器不支持,你自己改回去
        Employee &operator=(const Employee&) {} //这里是c++14的写法,我编译器不支持
    
        unsigned get_id() { return m_id;}
        std::string get_name() { return m_name;}
        static void init_id() { id = 0;}
    private:
        unsigned m_id;
        std::string m_name;
    };
    
    unsigned Employee::id = 0; //这里加上
    
    int main() {
        Employee::init_id();
        Employee a("wu"), b("sun"), c("liu");
        std::cout << a.get_id() << " and " << a.get_name() << std::endl;
        std::cout << b.get_id() << " and " << b.get_name() << std::endl;
        std::cout << c.get_id() << " and " << c.get_name() << std::endl;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退