C++ 是否可以在c+;中的类中递增全局变量+;?
我想在C++类中增加一个全局变量,但不能配置如何做< /p>C++ 是否可以在c+;中的类中递增全局变量+;?,c++,C++,我想在C++类中增加一个全局变量,但不能配置如何做< /p> int line = 0; int ivar = 0; int cvar = 0; int svar = 0; class file { protected: char name[50]; string read; string write; ifstream readfile; ofstream writefile; int i; int j; }; 我想在类文件中增加cv
int line = 0;
int ivar = 0;
int cvar = 0;
int svar = 0;
class file {
protected:
char name[50];
string read;
string write;
ifstream readfile;
ofstream writefile;
int i;
int j;
};
我想在类文件中增加cvar变量。差不多
class file {
protected:
char name[50]; cvar++;
string read;
string write;
ifstream readfile;
ofstream writefile;
int i;
int j;
};
但如果这样做,编译器会给出错误。有人能想出一种替代方法来实现这一点吗?您不能将要执行的代码行放入类定义中。它们需要在一个函数中 也许在您的情况下,构造函数:
class file {
public:
file() {
cvar++;
}
protected:
char name[50];
string read;
string write;
ifstream readfile;
ofstream writefile;
int i;
int j;
};
有几种比全局变量更好的方法-这取决于您试图实现的目标。您可以,但增量需要在类的方法中 使用默认构造函数是可行的,这样做的好处是,在创建类的新实例时,会发生增量:
file::file() /*ToDo - declare this in the class definition*/
{
cvar++;
}
最后,最好使用std::atomic
作为cvar
的类型,以防止并发问题(即在cvar
上同时读写)
我正在尝试为我的程序添加一个计数器,用于计算
完整程序中声明的字符类型变量
全局变量不好。此外,无论何时使用char[]
都“手动”递增计数器也不好。我可能会使用类似的方法:
struct MyString {
std::string theString;
static int counter;
MyString() { counter++;}
};
int MyString::counter = 0;
然后
struct file {
MyString name;
/*...*/
};
static
变量的行为或多或少类似于一个全局变量,但它不会污染您的名称空间,因为它就是它所属的名称空间(MyString::counter
)。此外,如果使用MyString
,您就不会忘记在每次需要字符串时递增计数器。最后但并非最不重要的一点是,我将char[]
更改为std::string
,因为除非有原因,std::string
应该优先于char[]
,您可以在类方法内部增加它。全局变量也不好。不能在类声明中放入任意代码。至于提出替代方案,我们必须知道你想要实现什么。(注意:ivar
、cvar
和svar
都是错误的变量名),但如果这样做,编译器会给出错误。你试过了吗。。我不知道。。读取错误?这可能给了你一个关于你做错了什么的线索。@AlgirdasPreidžius错误说“这个声明没有类或类型说明符”。@Borgleader我试图在我的程序中添加一个计数器,计算完整程序中声明的字符类型变量的数量。