0

我用指针创建了一个向量,并在一个名为的方法中从从 Modul 派生的类 DigOut 创建了新对象

BOOL Cbeckhoff_frontendDlg::OnInitDialog()
{
//...
std::vector<Modul*> arrDigOut;
arrDigOut.push_back(new DigOut(IDC_CHECK1, this,"GVL.DigOut1",pAddr));
//...
for(iNumDO = 0;iNumDO<1;iNumDO++) arrDigOut[iNumDO]->InitCheck(this);
//...
}

如何从不同的方法访问向量,例如:

void Cbeckhoff_frontendDlg::OnBnClickedButton3()
{
for(iNumDO = 0;iNumDO<1;iNumDO++) arrDigOut[iNumDO]->SetID();
}

我考虑过使用公共指针或 setter 和 getter,
但我不会像这样创建成员变量:

std::vector<Modul*> *   parrDigOut;

在抱怨的地方,没有声明 Modul。

4

3 回答 3

0

如果我理解正确,只需将其公开并在其前面添加此行:

class Modul;
于 2012-07-18T15:13:19.867 回答
0

Your example gives the impression you are declaring the vector at function scope. Its lifetime ends at the end of the function call (and all memory is leaked). Store it as a class member and a member functions begin and end that forward to the begin and end member functions of the vector. Possibly wrap them in a dereference_iterator to hide the fact that they are pointers.

class foo {
public:
  foo() { 
    // add things to s_
  }

  ~foo() { 
    // dont forget to delete everything in s_
  }
  typedef std::vector<my_stuff*>::iterator iterator;
  typedef std::vector<my_stuff*>::const_iterator const_iterator;
  iterator begin() { return s_.begin(); }
  iterator end() { return s_.end(); }
  const_iterator begin() const { return s_.begin(); }
  const_iterator end() const { return s_.end(); }

  // or to hide the pointers
  typedef boost::indirect_iterator< std::vector<my_stuff*>::iterator > iterator;
  iterator begin() { return boost::make_indirect_iterator(s_.begin()); }
  iterator end() { return boost::make_indirect_iterator(s_.end()); }
private:
  std::vector<my_stuff*> s_;
};
于 2012-07-18T15:16:46.730 回答
0

You could define a member variable as you described. On top of the class declaration just provide a forward declaration,

class Modul;

This is to let the compiler know that such a class is going to get defined somewhere down the line.

The member variables need not be public as it is accessed from another function in the same class.

And just declare the member as:

std::vector<Modul*>   parrDigOut; //No need of pointers

However, you could think of using a smart pointer to make sure that it gets deleted when the parent class gets out of scope

于 2012-07-18T15:17:10.487 回答