如何在C ++中初始化构造函数内的对象?

时间:2017-02-10 22:40:49

标签: c++

我已经使用RectangleShape对象作为私有对象创建了播放器类,我想在.cpp contstructor中初始化它,但它不起作用。

player.h:

#pragma once

#include <SFML/Graphics.hpp>

class Player {
    Player(int x, int y);

    private:
        int x;
        int y;
        sf::RectangleShape rect;

    public:
        void Move(int x, int y);
        void Update();
        void Render(sf::Window window);
};

这是player.cpp:

#include "player.h"
#include <SFML/Graphics.hpp>

Player::Player(int x, int y) {
    this->x = x;
    this->y = y;
    this->rect(sf::Vector3f(x, y)); //Sorry, this one is the one that doesn't work.
}

1 个答案:

答案 0 :(得分:2)

您应该使用构造函数初始化列表。例如像这样;

班级定义

(?:\W+(\d+))?

班级实施

class Player 
{
    Player(int x, int y);

    private:
        int x;
        int y;
        //other code...
};