【问题标题】:C++ must define as static constexpr double - cant initialize static non-integral variable inside ClassC++ 必须定义为 static constexpr double - 不能在 Class 内初始化静态非整数变量
【发布时间】:2019-06-27 06:08:21
【问题描述】:

// 我在其他有关静态变量及其初始化的问题中找到了有用的信息。我找到了一个解决方法(不觉得像这里建议的那样用一个单独的文件来解决这个问题:Initialize static variables in C++ class?),但这将是一个解决方案,以便能够使用静态变量作为累加器在特定实例上执行的操作通过他们的方法。

很抱歉浪费了时间,我认为这个问题对社区没有任何价值,应该关闭。

尝试打印两个静态累加器的静态函数 mostrarTotal() 不起作用,因为它们的定义不正确。


class Vendedor {
    private:
        static double sumatot;
        static double comtot;
    public:
        static void mostrarTotal();
};

//Static method to print static variables sumatot and comtot
void Vendedor :: mostrarTotal() {
    cout << "Las ventas totales fueron: " << sumatot << " para una comisión de: " << comtot;
}

int main () {

//This line throws the error
    Vendedor::mostrarTotal();

    return 0;
}

【问题讨论】:

标签: c++ static-functions


【解决方案1】:

在你的情况下,你应该调用像 ClassName::functionName() 这样的静态函数:

Vendedor::mostrarTotal();

【讨论】:

  • 现在发生这种情况 /tmp/ccZ4ZNRb.o:在函数 Vendedor::setVentas()': main.cpp:(.text+0xd2): undefined reference to Vendedor::sumatot' main.cpp:(.text+0xdf):未定义引用 Vendedor::sumatot' /tmp/ccZ4ZNRb.o: In function Vendedor::mostrarTotal( )': main.cpp:(.text+0x1e0): 未定义引用Vendedor::comtot' main.cpp:(.text+0x1e7): undefined reference to Vendor::sumatot'
  • 好吧,你应该初始化你的类的静态成员变量。我不知道您项目的文件结构,但是在您的主要功能之前添加这两行应该可以解决您的问题: double Vendor::sumatot = 0;双供应商::comtot= 0;
猜你喜欢
  • 1970-01-01
  • 2020-09-20
  • 2014-06-20
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多