如何访问另一个源文件中 'struct' 的静态成员
How to access static member of a 'struct' in another source file
我正在创建一个小程序来进行计费。我正在尝试访问另一个源文件中头文件中声明的静态成员 static double total 。 Java 是我的第一语言,所以在用 C++ 整理它时遇到了麻烦。
当我尝试时出现以下错误。
bill.cpp(16): error C2655: 'BillItem::total': definition or redeclaration illegal in current scope
bill.h(8): note: see declaration of 'BillItem::total'
bill.cpp(16): error C2086: 'double BillItem::total': redefinition
bill.h(8): note: see declaration of 'total'
我怎样才能让它可用。谷歌搜索错误没有帮助。
我想要实现的是在一个结构中创建一个静态双精度变量,它对所有结构实例都是通用的。我需要在我将进行计算的另一个源文件中访问这个静态变量。
Bill.h
#pragma once
struct BillItem
{
public:
static double total;
int quantity;
double subTotal;
};
Bill.cpp
#include<iostream>
#include "Item.h"
#include "Bill.h"
void createBill() {
double BillItem::total = 10;
cout << BillItem::total << endl;
}
MainCode.cpp
#include <iostream>
#include "Bill.h"
int main() {
createBill();
return 0;
}
您还没有申报总数。好吧,你有,但是在一个函数中。它需要在函数范围之外:
#include<iostream>
#include "Item.h"
#include "Bill.h"
double BillItem::total = 0;
void createBill() {
BillItem::total = 10;
cout << BillItem::total << endl;
}
我正在创建一个小程序来进行计费。我正在尝试访问另一个源文件中头文件中声明的静态成员 static double total 。 Java 是我的第一语言,所以在用 C++ 整理它时遇到了麻烦。
当我尝试时出现以下错误。
bill.cpp(16): error C2655: 'BillItem::total': definition or redeclaration illegal in current scope
bill.h(8): note: see declaration of 'BillItem::total'
bill.cpp(16): error C2086: 'double BillItem::total': redefinition
bill.h(8): note: see declaration of 'total'
我怎样才能让它可用。谷歌搜索错误没有帮助。
我想要实现的是在一个结构中创建一个静态双精度变量,它对所有结构实例都是通用的。我需要在我将进行计算的另一个源文件中访问这个静态变量。
Bill.h
#pragma once
struct BillItem
{
public:
static double total;
int quantity;
double subTotal;
};
Bill.cpp
#include<iostream>
#include "Item.h"
#include "Bill.h"
void createBill() {
double BillItem::total = 10;
cout << BillItem::total << endl;
}
MainCode.cpp
#include <iostream>
#include "Bill.h"
int main() {
createBill();
return 0;
}
您还没有申报总数。好吧,你有,但是在一个函数中。它需要在函数范围之外:
#include<iostream>
#include "Item.h"
#include "Bill.h"
double BillItem::total = 0;
void createBill() {
BillItem::total = 10;
cout << BillItem::total << endl;
}