2

これは私のヘッダーファイルです、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();
}

そしてこれが私のメインファイル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;
    }

印刷しようとしています(cout)2 2 2 2 3 4

エラー:

エラー

私の間違いは、ヘッダーファイルでvoidを使用しているだけだと感じています。コードが機能するようにヘッダーファイルを変更するにはどうすればよいですか?

参照:learncppからのコード

4

2 に答える 2

7

同じ名前とパラメーターで2つの関数を宣言することはできません。

 void IncrementAndPrint()
于 2012-12-21T21:13:30.777 に答える
5

変数とは異なり、関数に新しい値を与えることはできません。したがって、コンパイラは次のように考えます。

「ああ、わかりました。あなたが言うとき、IncrementAndPrintあなたが意味するのは、ここでファイルの先頭にあるこの関数です」。

次に、それがprint_auto何を意味するのかを見て学習します。しかし、それがIncrementAndPrint実際にはこの他の関数を意味していることを伝えようとすると、コンパイラーは混乱します。「しかし、あなたはすでに私に何IncrementAndPrintを意味するのか教えてくれました!」とコンパイラは不平を言います。

これは、次のように言うことができる変数(何らかの方法で)とは対照的です。

int x = 0;
x = 6;

コンパイラーは、ある時点でx値がであることを理解しますが、「今は違う、それは。を意味します」0と言います。ただし、次のように言うことはできません。x6

int x = 0;
int x = 6;

変数名の前に型を含めると、新しい変数を定義することになります。タイプを含めない場合は、古いタイプに割り当てるだけです。

IncrementAndPrint別の名前を付ける必要があります。

または、たとえば、void IncrementAndPrint(int x);対など、異なる引数を取るようにすることもできますvoid IncrementAndPrint(double y);。議論は必要ないので、ここではお勧めしません。

もう1つの可能性は、名前空間を使用することです。次のようになります。

namespace automatic_variables {

void IncrementAndPrint() {
    // automatic variable version
}
void print() {
    // automatic version
}
}
namespace static_variables {

void IncrementAndPrint() {
    // static variable version
}
void print() {
    // static version
}
}
于 2012-12-21T21:22:49.323 に答える