简体   繁体   English

需要帮助使用boost在类定义中为向量分配空间

[英]Need help allocating space for vector within class definition using boost

I am trying to allocate space for a boost vector type in a class definition. 我正在尝试在类定义中为升压向量类型分配空间。 I am not a good c++ programmer, but shown below is my best attempt. 我不是一个好的C ++程序员,但是下面显示的是我的最佳尝试。 There are no error messages, but when I try to access the vector from my main function it believes that the vector has zero elements. 没有错误消息,但是当我尝试从主函数访问向量时,它认为向量具有零个元素。 I know this is because I did not tell the compiler how much space to allot when I declared the vector in the class definition, but I do not know how to do this without getting an error. 我知道这是因为在类定义中声明矢量时我没有告诉编译器要分配多少空间,但是我不知道如何做到这一点而不会出错。 I tried to circumvent this by telling it how big I wanted it in the constructor, but I know the compiler treats this as a redefinition that does not exist outside of the scope of the constructor. 我试图通过告诉它在构造函数中有多大来规避此问题,但是我知道编译器将此视为重新定义,但在构造函数范围之外不存在。 Can someone lead me in the right direction? 有人可以指引我正确的方向吗? Thanks in advance. 提前致谢。

namespace ublas = boost::numeric::ublas;

class Phase
{
 ublas::vector<cdouble> lam;
public:
 // Constructor:
 Phase()
 {
  ublas::vector<cdouble> lam(2);

  for(int i = 0; i < 2; i++)
  {
   lam(i) = 1.0;
  }
 }
 // Destructor:
 ~Phase() {}
 // Accessor Function:
 ublas::vector<cdouble> get_lam() { return lam; }
};

In your constructor you are creating a local variable lam that shadows the class variable lam . 在构造函数中,您正在创建一个局部变量lam ,该局部变量lam遮盖了类变量lam You want to initialize the vector in the constructor's initialization list: 您要在构造函数的初始化列表中初始化向量:

Phase() : lam(2)
{
 for(int i = 0; i < 2; i++)
 {
  lam(i) = 1.0;
 }
}

This calls the vector constructor you want as the class is being initialized, instead of the default constructor for the class. 这将在初始化类时调用所需的vector构造函数,而不是该类的默认构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM