簡體   English   中英

C2572 - 當嘗試在另一個文件中包含一個帶有默認參數的函數,然后將此文件包含在 main 中時

[英]C2572 - When trying to include a function with a default parameter in another file, and then include this file in main

我正在嘗試用 C++ 構建一個小程序,以了解預處理器指令以及它們的實際工作方式。

該程序由 5 個文件組成: main.cppfile1.hfile1.cppfile2.hfile2.cpp

file1.h中,我聲明了 1 個具有默認參數和新類型字節的函數:

typedef unsigned char byte;

byte f1(byte a, byte b = 5);

file1.cpp中,我定義了它:

#include "file1.h"

byte f1(byte a, byte b) {

    return a + b;
}

file2.h中,我聲明了第二個使用f1()的函數,並且始終將 10 作為第二個參數傳遞給它:

#include "file1.h"

byte f2(byte a);

同樣,在file2.cpp中,我定義了它:

#include "file2.h"

byte f2(byte a) {

    return f1(a, 10);
}

最后,這是主文件:

#include <iostream>
using namespace std;

#include "file1.h"

int main() {

    cout << f1(3) << endl;

    return 0;
}

現在,一切正常,輸出只是8

但是假設我需要在我的主文件中使用f2()函數,為此我包含了file2.h ,所以主文件現在是:

#include <iostream>
using namespace std;

#include "file1.h"
#include "file2.h"

int main() {

    cout << (int) f1(3) << endl;

    cout << (int) f2(2) << endl;

    return 0;
}

編譯器給出此錯誤: Error C2572 'f1': redefinition of default argument: parameter 1

由於file1.h包含在file2.h中,現在f1()file2.h中重新聲明,並且b參數也設置為5

如果我們假設我不能將f2()聲明和定義分別移動到file1.hfile1.cpp ,我該怎么做才能防止重新定義?

注意:我知道我可以使用#pragma once指令,但我試圖在沒有它的情況下解決這個問題,因為我正在嘗試專業地學習 C++ 指令。

在顯示的代碼中,當file1.hfile2.h都被#include 'd 時, bytef1()main.cpp中被聲明了多次。

根據 C++ 標准, §8.3.6 [dcl.fct.default]/4

[注意 2:默認參數不能由以后的聲明重新定義(甚至不能重新定義為相同的值)( [basic.def.odr] )。 ——尾注]

這正是這里發生的事情。

注意:我知道我可以使用#pragma once指令,但我試圖在沒有它的情況下解決這個問題,因為我正在嘗試專業地學習 C++ 指令。

使您的.h文件具有適當的標頭保護(參見#pragma once vs include guards? )是避免重新聲明的正確且專業的方法,例如:

file1.h

#ifndef File1H
#define File1H

typedef unsigned char byte;

byte f1(byte a, byte b = 5);

#endif

file2.h

#ifndef File2H
#define File2H

#include "file1.h"

byte f2(byte a);

#endif

在線演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM