u014786409
小飞将
采纳率66.7%
2019-10-03 23:48

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条回答

  • caozhy 从今以后生命中的每一秒都属于我爱的人 2年前

    通过编译:

    #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;
    }
    
    点赞 2 评论 复制链接分享
  • JonathanYan JonathanYan 2年前

    静态变量需要在类外部进行初始化。

    unsigned Employee::id = 0;
    

    这句不需要写在构造函数里,写在头文件对应的cpp里就行。

    点赞 2 评论 复制链接分享

相关推荐