繁体   English   中英

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

[英]How can I initialize an object inside a constructor in C++?

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

播放器.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.
}

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

类定义

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

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

类实现

    Player(int x, int y)
    :x(x), y(y)
    {
        //Constructor body
    }

暂无
暂无

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

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