2017-04-19 106 views
1

我想计算已使用某个构造函数创建的对象的数量。我之前在C#之类的语言中这样做过,所以我创建了一个static int变量,我在构造函数中递增。C++静态变量声明奇怪的链接器错误

之前,我告诉你的代码 - 这里是compilement错误:

Severity Code Description Project File Line Suppression State Error LNK2001 unresolved external symbol "private: static int Bill::count_of_created_bills" ([email protected]@@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; 
    } 
}; 

的compilement错误occurrs如果我包括这行:

Bill b(1, 2, 3);

回答

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;