C ++静态变量声明奇怪的链接器错误

时间:2017-04-19 14:19:16

标签: c++ constructor static linker

我想计算使用某个构造函数创建的对象的数量。我之前用C#这样的语言完成了这个,所以我创建了一个static int变量,我在构造函数中递增。

在我向您展示代码之前 - 这是编译错误:

  

严重级代码描述项目文件行抑制状态   错误LNK2001未解析的外部符号“private:static int Bill :: count_of_created_bills”(?count_of_created_bills @ Bill @@ 0HA)Ausgabenverwaltung c:\ Users \ xy \ documents \ visual studio 2017 \ Projects \ Ausgabenverwaltung \ Ausgabenverwaltung \ Ausgabenverwaltung.obj 1

以下是代码:

#pragma once
class Bill
{
private:
    static int count_of_created_bills;
    int id;               // Unique Identification
    double ammount;       // Ammount of bill    
    int month;            // Month of bill (January = 0, February = 1 ...)
    int type_of_spending; // Type of spending (Food = 0 ...) 
public:
    Bill(int a, int m, int t):ammount(a), month(m), type_of_spending(t)
    {
        count_of_created_bills++;
        id = count_of_created_bills;
    }
};

如果我包含这一行,则会发生编译错误:

Bill b(1, 2, 3);

1 个答案:

答案 0 :(得分:1)

你忘了添加初始化:

Bill::Bill(int a, int m, int t):ammount(a), month(m), type_of_spending(t)
    {

        std::cout << "::Ros-App!" << Foo::count_of_created_bills << std::endl;
        Foo::count_of_created_bills++;
        id = count_of_created_bills;
    }
int Bill::count_of_created_bills = 0;
相关问题