简体   繁体   中英

Call constructor from other method in C++

I am not sure is that legal or not in 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++? 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:

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. 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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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