【问题标题】:C++ Static Variable Declaration Weird Linker Error [duplicate]C ++静态变量声明奇怪的链接器错误[重复]
【发布时间】: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


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2012-03-06
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      相关资源
      最近更新 更多