首页 文章

在头文件中声明一个类,并从用户输入初始化该类的数组

提问于
浏览
2

请参阅下面我的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);
}

1 回答

  • 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();
    }
    

    EDIT: 为了回应Klaus ' complaint I thought I' d添加初始化的解释,我正在评论 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
    

相关问题