declaration/initialization C++ 中多个文件的问题
declaration/initialization issue with multiple files in C++
我知道如何从第二个 .cpp 文件调用一个简单的函数(即 add(int x, int y){return x+y;}
,仅此而已)。
现在我想更进一步,遇到以下问题:
在我的 main.cpp 中,我得到了这样一行(重要的部分是最后的变量 a_wt):
transform(a_att.begin(), a_att.end(), a_att.begin(), std::bind1st(std::multiplies<float>(), a_wt));
所以,但现在我得到了第二个 .cpp 文件,我在其中放置了大量重复代码,要求在 void 函数中输入。 (你可以想象像 "apple_prize?" cin >> ... "cherry_prize?" cin >> ...
太长了,我想把这个块放在一个额外的文件中,以减轻 main.cpp 的可读性。在 main()
的最开始,我正在写 void prizes();
以在其中包含该过程)。
所以在第二个 .cpp 文件中有类似 std::cin >> a_wt;
的东西。
除其他事项外,我在头文件中声明了 int a_wt;
并将此头文件放入两个 .cpp 文件中。
编译 main.cpp 时出现错误“ 未初始化的局部变量 'a_wt' 使用 ”。
如何让 main.cpp 文件看到它应该有耐心,并且在上面的 transform
行中使用它之前,它会在第二个 .cpp 中正确初始化?我认为头文件将确保两个 .cpp 文件将 "see" 彼此。
(代码通常是 运行,而我全部都在 main.cpp 中)。
非常感谢您的帮助!
ps:关于将大量不重要的代码导出到第二个 .cpp 文件;除了将它放在第二个文件的 void 函数中之外,还有其他方法吗?
一些链接就足够了,因为我愿意自己学习,不想占用你太多时间。
有点不清楚您要做什么,但考虑在 header 中将变量声明为 extern int a_wt;
,然后在一个 .cpp 文件中定义它,并确保您在两者中都包含 header 。例子
// header.h
extern int a_wt;
// file1.cpp
#include "header.h"
int a_wt = 42; // need the definition in one translation unit
// file2.cpp
#include "header.h"
// file2 has access to a_wt now
如果你想用更复杂的东西初始化全局变量,那么你可以将它定义成一个函数 static
而不是使它成为 extern
并将它用作该函数的结果, 喜欢
// header.h
int get_a_wt();
// file1.cpp
#include "header.h"
int get_a_wt()
{
static int a_wt;
// initialize it here
return a_wt;
}
// file2.cpp
#include "header.h"
// use get_a_wt() instead of a_wt
int something = get_a_wt();
但是,尽量减少全局变量的使用,因为它们会使您的代码更难阅读、更少本地化,并且容易产生严重的副作用。
我知道如何从第二个 .cpp 文件调用一个简单的函数(即 add(int x, int y){return x+y;}
,仅此而已)。
现在我想更进一步,遇到以下问题:
在我的 main.cpp 中,我得到了这样一行(重要的部分是最后的变量 a_wt):
transform(a_att.begin(), a_att.end(), a_att.begin(), std::bind1st(std::multiplies<float>(), a_wt));
所以,但现在我得到了第二个 .cpp 文件,我在其中放置了大量重复代码,要求在 void 函数中输入。 (你可以想象像 "apple_prize?" cin >> ... "cherry_prize?" cin >> ...
太长了,我想把这个块放在一个额外的文件中,以减轻 main.cpp 的可读性。在 main()
的最开始,我正在写 void prizes();
以在其中包含该过程)。
所以在第二个 .cpp 文件中有类似 std::cin >> a_wt;
的东西。
除其他事项外,我在头文件中声明了 int a_wt;
并将此头文件放入两个 .cpp 文件中。
编译 main.cpp 时出现错误“ 未初始化的局部变量 'a_wt' 使用 ”。
如何让 main.cpp 文件看到它应该有耐心,并且在上面的 transform
行中使用它之前,它会在第二个 .cpp 中正确初始化?我认为头文件将确保两个 .cpp 文件将 "see" 彼此。
(代码通常是 运行,而我全部都在 main.cpp 中)。
非常感谢您的帮助!
ps:关于将大量不重要的代码导出到第二个 .cpp 文件;除了将它放在第二个文件的 void 函数中之外,还有其他方法吗? 一些链接就足够了,因为我愿意自己学习,不想占用你太多时间。
有点不清楚您要做什么,但考虑在 header 中将变量声明为 extern int a_wt;
,然后在一个 .cpp 文件中定义它,并确保您在两者中都包含 header 。例子
// header.h
extern int a_wt;
// file1.cpp
#include "header.h"
int a_wt = 42; // need the definition in one translation unit
// file2.cpp
#include "header.h"
// file2 has access to a_wt now
如果你想用更复杂的东西初始化全局变量,那么你可以将它定义成一个函数 static
而不是使它成为 extern
并将它用作该函数的结果, 喜欢
// header.h
int get_a_wt();
// file1.cpp
#include "header.h"
int get_a_wt()
{
static int a_wt;
// initialize it here
return a_wt;
}
// file2.cpp
#include "header.h"
// use get_a_wt() instead of a_wt
int something = get_a_wt();
但是,尽量减少全局变量的使用,因为它们会使您的代码更难阅读、更少本地化,并且容易产生严重的副作用。