【问题标题】:Declaring a class in a header file, and initializing an array of the class from user input在头文件中声明一个类,并根据用户输入初始化该类的数组
【发布时间】:2015-01-24 00:08:09
【问题描述】:

请看下面我的 c++ 代码的 sn-p。因为 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);
}

【问题讨论】:

  • 给构造函数一个参数。用它来初始化向量。
  • 您能详细说明一下吗?
  • 你能告诉我们你的意图是什么吗?您的类定义永远不会在您的代码中使用。请了解如何初始化全局对象/数据! c++ 中没有任何内容可以使句子“foo.h 在”之前执行正确。您的应用程序的启动代码在进入 main 之前初始化所有全局数据。但是初始化的顺序或多或少是未定义的,并且取决于您的编译器和链接器设置以及链接期间文件的顺序。用数字初始化一个向量会创建一个给定大小的向量,而不是里面的值!

标签: c++ arrays


【解决方案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 &gt; 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

【讨论】:

  • 你的apple foo = num == 0 ? apple() : apple(num); 对我来说看起来很脏。这里有一个初学者在问,你提供了一个几乎不可读的代码。而且我认为初始化一个大向量并将其分配给另一个实例的已经给定实例并不是一个好主意,这可能会导致大量复制操作。
  • @Klaus 我做了“几乎不可读的代码被剪断”,所以我不必复制。取决于您的编译器可能会转换为移动,但通常编译器只会将其视为我只是直接调用了该 ctor。
  • 你是对的:它可能被优化了。但是代码可以写得更简单,你可以避免任何复制而没有优化的希望。为什么要在 apple() 和 apple(num) 之间做出选择?默认构造函数也会产生一个空向量,它与 apple(0) 相同。因此,您的代码可能会产生一个糟糕/缓慢的可执行文件,而没有任何需要或好处。
  • 感谢您的回答@JonathanMee。如果我有 3 个向量 RedApple(num1)、GreenApple(num2)、BlueApple(num3),我应该如何传递 num1、num2 和 num3?是不是像 apple(int num1, int num2, int num3): RedApple(num1), GreenApple(num2), BlueApple(num3){} ?非常感谢!
  • @goosli 是的,与其有一个只需要 1 个变量的构造函数,你需要一个需要 3 个变量的构造函数。所以它看起来像:apple(int num1, int num2, int num3) : RedApple(num1), GreenApple(num2), BlueApple(num3) {} 你还需要检查所有三个变量您的电话:apple foo = num1 &gt;= 0 &amp;&amp; num2 &gt;= 0 &amp;&amp; num3 &gt;= 0 ? apple(num1, num2, num3) : apple();
猜你喜欢
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多