我的程序有什么问题

时间:2014-03-15 16:57:25

标签: c++ class constructor

class blueprint1{
private:
    int serialnum;
    int static tracker=0;
public:
    blueprint1(){
        tracker += 1;
    }
    void output(){
        serialnum = tracker;
        cout << "The serial number of object is "<<serialnum<< endl;
    }
};

int main()
{

    blueprint1 one;
    one.output();
    blueprint1 two;
    two.output();
}

它给了我errorError 1 error LNK2001: unresolved external symbol "private: static int blueprint1::tracker" (?tracker@blueprint1@@0HA)

2 个答案:

答案 0 :(得分:2)

您必须在类声明之外实际定义静态类变量。因此,在cpp文件中添加以下行:

int blueprint1::tracker=0;
编辑:对不起,我在写完正确的代码行之前意外地答应了我的答案

答案 1 :(得分:0)

请参阅代码中静态变量的初始化 它应该初始化为int blueprint1::tracker = 0;

class blueprint1{
    private:
        int serialnum;
        int static tracker;
    public:
        blueprint1(){
            tracker += 1;
        }
        void output(){
            serialnum = tracker;
            cout << "The serial number of object is "<<serialnum<< endl;
        }
    };

    int blueprint1::tracker = 0; //this is the way you should initialize static variable 

    int main()
    {

        blueprint1 one;
        one.output();
        blueprint1 two;
        two.output();
    }