简体   繁体   English

从C ++中的其他方法调用构造函数

[英]Call constructor from other method in C++

I am not sure is that legal or not in C++: 我不确定在C ++中是否合法:

class Image
{
     Image(int w, int h) // constructor
     {
            ...
     }

     Image GetSpecialImage()
     {
          Image rVal(10,10);
          return rVal;
     }
}

Do I need to use another middle level init() method to do this in C++? 我是否需要使用另一个中级init()方法在C ++中执行此操作? If yes, can you please show me how? 如果是,请您告诉我如何?


EDIT: Eventhough you say it's fine, it does not really do what I want to do... Let me give you some more code: EDIT:即使您说很好,它也并没有真正做我想做的...让我给您更多代码:

class Image
{
     float* data;
     int w;
     int h;

     Image(int w, int h) // constructor
     {
            this->w = w;
            this->h = h;
            data = (float*) malloc ( w * h * sizeof(float) );
     }

     Image GetSpecialImage()
     {
          Image rVal(this->w,this->h);

          for(i=0;i<this->w * this->h;i++)
          {
                rVal.data[i] = this->data[i] + 1;
          }

          return rVal;
     }
}

int main()
{
      Image temp(100, 100);
      Image result = temp.GetSpecialImage();
      cout<<result.data[0];

      return 0;
}

Is there anything wrong with this part? 这部分有什么问题吗?

As Seth said, that is legal. 正如塞思所说,那是合法的。

Something you could change to make it work even better is to make GetSpecialImage a static function. 为了使它更好地工作,您可以进行一些更改,使GetSpecialImage成为静态函数。 A static function defined in a class is a class function instead of an object function. 在类中定义的静态函数是类函数,而不是对象函数。 That means you don't need an object in order to call it. 这意味着您不需要对象即可调用它。

It would then be called like this: Image special = Image::GetSpecialImage(); 然后将这样称呼它: Image special = Image::GetSpecialImage();

Yes, you can do this. 是的,您可以这样做。 I would just do this though 我只是这样做

 Image GetSpecialImage()
 {            
     return Image(10,10);      
 } 

While there's nothing wrong with this code (well, except for returning a local, which is a no-no), I guess what you're looking for is a static constructor pattern. 虽然这段代码没有任何问题(好吧,除了返回本地,这是一个不行),但我猜您正在寻找的是静态构造函数模式。 Like so: 像这样:

class Image{
 public:
  static Image* GetSpecialImage(){
    return new Image(10,10);
  }
};

//and call it so
Image *i = Image::GetSpecialImage();

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

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