-4

我有点新手,所以这里的一些帮助将不胜感激。我有一个名为 Device 的类,它获取设备屏幕大小:

int Device::GetDisplay()
{
 DisplayInfo display;
 int displayArray [2];
 displayArray[0] = display.pixelSize().width();
 displayHeight[1] = display.pixelSize().height();

 return displayArray;
}

它返回一个数组,有没有更好的方法来返回数据?

还有一种更好的方法来调用这个类,它目前通过以下方式调用:

Device *device = new Device();
device.GetDisplay();

我可以在不使用设备的情况下调用它吗*device = new Device();

谢谢!

4

2 回答 2

3

Could I call it without using Device *device = new Device();

Yes, you can instantiate it on automatic storage:

Device device;

You should only use dynamic allocation if you really need it. It isn't clear from your example that you need it at all.

As for the rest of the question, there are too many errors to make ant sense out of it. But you could return a simple class holding the two pieces of information you want:

struct DisplayDimensions
{
  int height;
  int width;
};

DisplayDimensions Device::GetDisplay()
{
 DisplayInfo display;
 DisplayDimensions d;
 d.width = display.pixelSize().width();
 d.height = display.pixelSize().height();

 return d;
}
于 2012-10-28T17:52:31.637 回答
0

Your return value(int) does not match the value that returned from the function(int[2]), you should either use std::array or std::pair or something like that.

Since your function never use this you can make it static then you can call it without an instance of the class using Device::GetDisplay().

You should first mark your function as static:

static std::pair<int, int> GetDisplay() {
    DisplayInfo display;
    return std::make_pair(display.pixelSize().width(), display.pixelSize().height());
}

Then you can use Display::GetDisplay()

于 2012-10-28T17:52:15.340 回答