如何访问另一个源文件中“结构”的静态成员

Anj*_* Jo 4 c++ struct static-members

我正在创建一个小程序来进行计费。我正在尝试访问在另一个源文件中的头文件中声明的静态成员 static double total 。Java 是我的第一门语言,因此在用 C++ 对其进行分类时遇到了麻烦。

当我尝试时,出现以下错误。

bill.cpp(16):错误 C2655:'BillItem::total':定义或重新声明在当前范围内非法

bill.h(8):注意:参见'BillItem::total'的声明

bill.cpp(16): 错误 C2086: 'double BillItem::total': 重新定义

bill.h(8): 注意:见“total”的声明

我怎样才能使它可用。谷歌搜索错误没有帮助。

我想要实现的是在一个结构中创建一个静态双变量,这对所有结构实例都是通用的。我需要在另一个源文件中访问这个静态变量,我将在其中进行计算。

比尔.h

#pragma once

struct BillItem
{
public:
    static double total;
    int quantity;
    double subTotal;
};
Run Code Online (Sandbox Code Playgroud)

比尔.cpp

#include<iostream>
#include "Item.h"
#include "Bill.h" 

void createBill() {
    double BillItem::total = 10;
    cout << BillItem::total << endl;
}
Run Code Online (Sandbox Code Playgroud)

主代码.cpp

#include <iostream>
#include "Bill.h"

int main() {
    createBill();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

nvo*_*igt 5

你还没有申报你的总数。嗯,你有,但在一个函数内。它需要在函数范围之外:

#include<iostream>
#include "Item.h"
#include "Bill.h" 

double BillItem::total = 0;

void createBill() {
    BillItem::total = 10;
    cout << BillItem::total << endl;
}
Run Code Online (Sandbox Code Playgroud)