请参阅下面我的c ++代码片段。因为foo.h是在int main(int argc,char * argv [])之前执行的,所以数组RedApple将初始化为0并导致错误。处理这个问题的最佳方法是什么?有没有办法在foo.h中保留类声明,但是从用户输入中在foo.cpp中初始化它?谢谢!
在foo.h中
#include <vector>
extern int num;
class apple
{
std::vector<long> RedApple;
public:
apple(): RedApple(num)
}
在foo.cpp
#include "foo.h"
int num;
int main(int argc, char *argv[])
{
sscanf_s(argv[1],"%d",&num);
}
答案 0 :(得分:1)
在foo.h中
#include <vector>
class apple
{
std::vector<long> RedApple;
public:
apple(){}
apple(int num): RedApple(num){}
}
在foo.cpp
#include "foo.h"
int main(int argc, char *argv[])
{
int num;
sscanf_s(argv[1],"%d",&num);
apple foo = num > 0 ? apple(num) : apple();
}
修改强>
在回复Klaus投诉时,我想我会添加初始化的解释,我正在评论第apple foo = num > 0 ? apple(num) : apple();
行,所以我会在每个单词上对其进行垂直评论:
apple // This is the type of variable in the same way int is the type of int num;
foo // The name of the apple object that I am creating
= // Normally this will trigger the assignment operator (but in a declaration line the compiler will optimize it out)
num > 0 ? // The condition to a ternary operator if true the statement before the : is executed if false the one after is executed
apple(num) // If num is greater than 0 use the non-default constructor
: apple(); // If num is less than or equal to 0 use the default number cause we can't initialize arrays negatively