提问人:X Y 提问时间:12/13/2022 最后编辑:Remy LebeauX Y 更新时间:12/14/2022 访问量:171
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.cpp
file1.h
file1.cpp
file2.h
file2.cpp
在 中,我声明了 1 个具有默认参数和新类型字节的函数:file1.h
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;
}
在 中,我声明了第二个函数,该函数使用 ,并且始终将 10 作为第二个参数传递给它:file2.h
f1()
#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.h
file1.cpp
注意:我知道我可以使用指令,但我正在尝试在没有它的情况下解决这个问题,因为我正在尝试专业地学习 C++ 指令。#pragma once
答:
在所示的代码中,并且正在多次声明 when 和 are both 'd.byte
f1()
main.cpp
file1.h
file2.h
#include
根据 C++ 标准,§8.3.6 [dcl.fct.default]/4:
[注 2:默认参数不能通过后面的声明重新定义(甚至不能重新定义相同的值)([basic.def.odr])。
这正是这里发生的事情。
注意:我知道我可以使用指令,但我正在尝试在没有它的情况下解决这个问题,因为我正在尝试专业地学习 C++ 指令。
#pragma once
使文件具有适当的标头保护(请参阅 #pragma 一次与包含保护?)是避免重新声明的正确且专业的方法,例如:.h
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
评论
f1()
b
#pragma once
int f(int a, int b #ifndef FILE1_H #define FILE1H = 5 #endif);
file1.h
评论
#include "file1.h"
file2.h
file2.h
file1.h
file2.cpp
file1.h
f1()
file2.h
file1.h
int
byte