在头文件中声明类,并根据用户输入初始化类的数组 请参阅下面的C++代码片段。因为foo.h是在int main(int argc,char*argv[])之前执行的,所以数组RedApple将被初始化为大小为0并导致错误。处理这个问题的最好办法是什么?有没有办法在foo.h中保留类声明,但从用户输入在foo.cpp中初始化它?谢谢

在头文件中声明类,并根据用户输入初始化类的数组 请参阅下面的C++代码片段。因为foo.h是在int main(int argc,char*argv[])之前执行的,所以数组RedApple将被初始化为大小为0并导致错误。处理这个问题的最好办法是什么?有没有办法在foo.h中保留类声明,但从用户输入在foo.cpp中初始化它?谢谢,c++,arrays,C++,Arrays,在福岛 #include <vector> extern int num; class apple { std::vector<long> RedApple; public: apple(): RedApple(num) } #include <vector> class apple { std::vector<long> RedApple; public: apple(){} apple(int num): RedAp

在福岛

#include <vector>
extern int num;
class apple
{
std::vector<long> RedApple;
public:
    apple(): RedApple(num)
}
#include <vector>

class apple
{
std::vector<long> RedApple;
public:
    apple(){}
    apple(int num): RedApple(num){}
}
在福岛

#include <vector>
extern int num;
class apple
{
std::vector<long> RedApple;
public:
    apple(): RedApple(num)
}
#include <vector>

class apple
{
std::vector<long> RedApple;
public:
    apple(){}
    apple(int num): RedApple(num){}
}
编辑: 作为对“投诉的回应,我想我应该添加一个初始化的解释,我在评论行
applefoo=num>0?”?苹果(num):苹果()因此我将垂直打断它,对每个单词进行注释:

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

给构造函数一个参数。用它来初始化向量。你能详细说明一下吗?你能告诉我们你的意图吗?您的类定义从未在代码中使用过。请了解全局对象/数据是如何初始化的!C++中没有任何东西使“Fo.h被执行之前”是正确的。应用程序的启动代码在进入main之前初始化所有全局数据。但是初始化的顺序或多或少是未定义的,这取决于编译器和链接器设置以及链接过程中文件的顺序。Init一个带数字的向量创建一个给定大小的向量,而不是里面的值!你的行
applefoo=num==0?apple():apple(num)对我来说看起来很脏。这里有一个初学者在问,您提供了一个几乎无法阅读的代码。我认为初始化一个大的向量并将其分配给另一个实例的一个已经给定的实例不是一个好主意,这可能会导致一个巨大的复制操作。@Klaus我做了“几乎不可读的代码剪切”,这样我就不必复制了。这取决于你的编译器,它可能会转换成一个移动,但通常编译器会把它当作我刚刚直接调用了那个ctor来处理。你是对的:它可能会被优化掉。但是代码可以编写得更简单,并且可以避免任何副本,而无需进行优化。为什么要在apple()和apple(num)之间做出选择?默认构造函数也会产生一个与apple(0)相同的空向量。因此,您的代码可能会产生一个糟糕/缓慢的可执行文件,而没有任何需要或好处。谢谢您的回答@JonathanMee。如果我有3个向量:红苹果(num1)、绿苹果(num2)、蓝苹果(num3),我应该如何通过num1、num2和num3?它像苹果(intnum1,intnum2,intnum3):红苹果(num1),绿苹果(num2),蓝苹果(num3){}?非常感谢@是的,与其让构造函数只接受1个变量,不如让构造函数接受3个变量。所以它看起来像:
apple(intnum1,intnum2,intnum3):红苹果(num1),绿苹果(num2),蓝苹果(num3){}
您还需要在调用中检查所有三个:
apple foo=num1>=0&&num2>=0&&num3>=0?苹果(num1,num2,num3):苹果()