簡體   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