【发布时间】:2017-04-19 14:19:15
【问题描述】:
我想计算使用某个构造函数创建的对象的数量。我之前用 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);
【问题讨论】:
标签: c++ constructor static linker