在构造函数中初始化向量 - C ++ [英] Initialization of vector in a constructor - C++

查看:116
本文介绍了在构造函数中初始化向量 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个类Settings(设置) 处理我用于模拟
的设置和一个执行模拟步骤的类Simulations。



我不能理解的是为什么这个代码't预期工作:

 类设置{
public:
int n; //一个数字我需要在我的类模拟中正确创建一个向量
// ...其余的代码构造函数等从文件读取值。
//一切正常,值被正确分配
}

类模拟{
public:
std :: vector< int> v;
设置* SP;

模拟(设置*);
}

Simulation :: Simulation(Settings * pS)
:SP(pS),v(std :: vector< int>(SP-& ){} //构造函数不起作用,
// v已初始化,但不是作为大小为n但为0的向量创建的。

我认为在使用构造函数时有一个问题,但我不明白为什么。



通过定义v在大括号内的工作正常,我只是好奇地知道为什么
定义它正确的方式不能按预期的工作!


解决方案

您不需要额外的向量:

  Simulation :: Simulation(Settings * pS)
:SP(pS),v(SP-> n,0){}

如果这不起作用,这不是你的代码。您确定 SP 是在类定义中 v 之前声明的吗?如果这也不起作用,请尝试使用 pS 而不是 SP


I'm struggling with the constructor of one of my classes do to a member that is not initialized properly.

I have a class "Settings" that handles the setting I use for my simulations and a class Simulations that performs the simulation steps.

What I can't understand is why this code doesn't work as expected:

      class Settings{ 
         public: 
           int n ; // a number I need to create properly a vector in my class simulation
           // ... rest of the code constructors etc to read values from files.
           // everything works fine and the values are assigned properly
       }

       class Simulation{
          public:
          std::vector<int> v ;
          Settings *SP;

          Simulation(Settings *);
        }

        Simulation::Simulation(Settings *pS) 
           :SP(pS), v(std::vector<int>(SP->n,0)) {}    // the constructor doesn't work,
    // v is initialized but it is not created as a vector of size n, but 0.

I think there is a problem in the way I use the constructor but I can't understand why.

By the way defining v inside the curly brackets works fine, I'm just curious to know why defining it the proper way doesn't work as expected!

Thanks a lot for the help!

解决方案

You don't need the extra vector:

Simulation::Simulation(Settings *pS) 
       :SP(pS), v(SP->n,0) {}

If this doesn't work, this isn't your code. Are you sure SP is declared before v in the class definition? If this also doesn't work, try with pS instead of SP.

这篇关于在构造函数中初始化向量 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆