1

I am currently learning OOP for a project I'm working on (I'm in highschool and have some experience with c++; this is my third 'large' (>3 months) c++ project.) I have the basics of C++ classes figured out and managed to make some of the classes for the project.

So these is my page.h header:

class cl_Page{
public:
  cl_Page(cl_LessonMoment *parent_param);
  cl_Page(cl_SoftRoot *parent_param);
  int parent_type;
  cl_LessonMoment *parent_lmoment;
  cl_SoftRoot *parent_softroot;

  char id[256];

  //<content>
  //Backgrounds.
  str_Color bgcolor;
  cl_Image bgimage;

  //Actual content
  vector<cl_Textbox> textboxes;
  vector<cl_Button> buttons;
  vector<cl_Image> images;
  //</content>
};

(include guards and such are not here, but they are in my project)

And this is my page.cpp:

cl_Page::cl_Page(cl_LessonMoment *parent_param){
  parent_lmoment = parent_param;
  parent_type = 1;
  id[0] = '\0';
  //bgimage(NULL);
  SetColor(bgcolor, 0x000000ff);
}

(the other constructor is similar, it just sets a different type of parent)

My problem is that I want to call the constructor to bgimage (which is of cl_Image class type) inside my cl_Page constructor. If I try this (uncomment the line in the constructor), obviously it won't work.

So yeah, how do I call the constructor now? I really need to construct every member along with the cl_Page object.

4

4 回答 4

3

如果要bgImage在构造函数中创建对象cl_Page,它必须是指针 (1),或者您应该使用构造函数的初始化列表 (2),在这种情况下,这可能是一个更好的解决方案。

1. - 字段是指向 cl_Image 的指针

bgImage = new cl_Image(nullptr);

2. - 使用构造函数的初始化列表

cl_Page::cl_Page(cl_LessonMoment *parent_param) :
      bgImage(nullptr) 
{
  parent_lmoment = parent_param;
  parent_type = 1;
  id[0] = '\0';
  SetColor(bgcolor, 0x000000ff);
}

在那里你可以阅读更多关于构造函数的初始化列表:http ://www.cprogramming.com/tutorial/initialization-lists-c++.html

于 2013-01-29T17:19:10.213 回答
2

您可以使用成员初始化列表来初始化变量:

cl_Page::cl_Page(cl_LessonMoment *parent_param)
: bgImage(NULL)
{
  parent_lmoment = parent_param;
  parent_type = 1;
  id[0] = '\0';
  SetColor(bgcolor, 0x000000ff);
}

事实上,这是在构造函数中设置数据的首选方式。

于 2013-01-29T17:16:18.710 回答
1
cl_Page::cl_Page(cl_LessonMoment *parent_param)
    : bgImage( nullptr )
{
  parent_lmoment = parent_param;
  parent_type = 1;
  id[0] = '\0';
  SetColor(bgcolor, 0x000000ff);
}
于 2013-01-29T17:15:48.160 回答
1

您需要像这样初始化您的成员:

cl_Page::cl_Page(cl_LessonMoment *parent_param)
: parent_lmoment(parent_param)
, parent_type(1)
, bgimage(NULL)
{
    id[0] = '\0';
    SetColor(bgcolor, 0x000000ff);
}

在构造函数的头部初始化指针这不是必需的,但我仍然推荐它。我还建议用 0 初始化另一个指针,如果您遇到错误,它可能会对您有所帮助;-)

于 2013-01-29T17:17:15.190 回答