recordedhandclaps
recordedhandclaps

Reputation: 15

Declare a variable to be instantiate at a class level, and used inside the class functions

Let's say I have this class. How should I declare/instantiate the image object so that I can use it with all functions without the need to pass it as an argument?

view.h

class AAView : public QGraphicsView {

public:
    explicit AAView();
    QGraphicsScene* currentScene;
    QImage image;
};

view.cpp

AAView::AAView() {

    int sizeX = 1280;
    int sizeY = 720;

    image(sizeX, sizeY, QImage::Format_RGB32);
}

void AAView::drawPoint(int x, int y) {
    image.setPixel(x, y, qRgb(255, 255, 100));
}

I got this error:

error: no match for call to '(QImage) (int&, int&, QImage::Format)'
     image(sizeX, sizeY, QImage::Format_RGB32);

But by removing the image variable from the header, this error disappeared.

Upvotes: 0

Views: 58

Answers (2)

cigien
cigien

Reputation: 60412

You appear to be trying to call the QImage constructor for image, but that's not the correct syntax.

You can replace it with the following line inside the constructor

image = QImage(sizeX, sizeY, QImage::Format_RGB32);

or preferably construct it in a member initializer list

AAView::AAView() : image(1280, 720, QImage::Format_RGB32) {}

Upvotes: 2

catnip
catnip

Reputation: 25408

If you want to construct image in that way (or any other), then the best way is to do it in the member initialiser list:

AAView::AAView() : image (1280, 720, QImage::Format_RGB32) { ...

Upvotes: 1

Related Questions