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

标签 c++ constructor static linker

<分区>

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

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

Severity Code Description Project File Line Suppression State Error LNK2001 unresolved external symbol "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;
    }
};

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

账单 b(1, 2, 3);

最佳答案

你忘了添加初始化:

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;

关于C++ 静态变量声明奇怪的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43498404/

相关文章:

wpf - DataTemplate 具有非空构造函数的 ViewModel ?

聚合子类中的Java构造函数

linux - 如何从 .o 和 .a 文件创建 .a?

java - 对于匿名对象,静态 block 不会被执行

c# - 由于继承是不可能的,有没有办法在静态类中重用代码?

c++ - 在确保翻译单元之间的可用性时是否弃用静态?

c++ - 简单的 makefile 生成实用程序?

c++ - 在 C++ 中将格式化的数值数据读取到数组

c++ - 从基础对象继承接口(interface)是一种好习惯吗?

Javascript - 创建对象数组并理解构造函数