2 c++
这是我的头文件,auto vs static.h
#include "stdafx.h"
#include <iostream>
void IncrementAndPrint()
{
using namespace std;
int nValue = 1; // automatic duration by default
++nValue;
cout << nValue << endl;
} // nValue is destroyed here
void print_auto()
{
IncrementAndPrint();
IncrementAndPrint();
IncrementAndPrint();
}
void IncrementAndPrint()
{
using namespace std;
static int s_nValue = 1; // fixed duration
++s_nValue;
cout << s_nValue << endl;
} // s_nValue is not destroyed here, but becomes inaccessible
void print_static()
{
IncrementAndPrint();
IncrementAndPrint();
IncrementAndPrint();
}
Run Code Online (Sandbox Code Playgroud)
这是我的主文件,namearray.cpp
#include "stdafx.h"
#include <iostream>
#include "auto vs static.h"
using namespace std;
int main(); // changing this to "int main()" (get rid of ;) solves error 5.
{
print_static();
print_auto();
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试打印(cout)2 2 2 2 3 4
错误:

我觉得我的错误就是在头文件中使用void.如何更改头文件以便我的代码可以工作?
参考:来自learncpp的代码
与变量不同,您无法为函数赋予新值.所以这是编译器的想法:
"哦,好的,当你说IncrementAndPrint,你的意思是这个函数在文件的顶部".
然后它看到print_auto并了解这意味着什么.但是你试着告诉它IncrementAndPrint实际意味着这个其他功能,并且编译器会感到困惑."但你已经告诉我IncrementAndPrint意味着什么!",编辑抱怨道.
这与变量(以某种方式)形成对比,你可以说:
int x = 0;
x = 6;
Run Code Online (Sandbox Code Playgroud)
编译器理解,在某一点上,它x具有值0,但是你说" x现在是不同的,它意味着6.".但是,你不能说:
int x = 0;
int x = 6;
Run Code Online (Sandbox Code Playgroud)
因为当您在变量名称之前包含类型时,您将定义一个新变量.如果您不包含类型,则只需分配旧类型.
你必须给出IncrementAndPrint一个不同的名字.
或者,您可以让他们采用不同的参数,例如,void IncrementAndPrint(int x);vs void IncrementAndPrint(double y);. 我不建议在这里,因为你不需要参数.
另一种可能性是使用命名空间.它看起来像这样:
namespace automatic_variables {
void IncrementAndPrint() {
// automatic variable version
}
void print() {
// automatic version
}
}
namespace static_variables {
void IncrementAndPrint() {
// static variable version
}
void print() {
// static version
}
}
Run Code Online (Sandbox Code Playgroud)