简体   繁体   English

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

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

I've created the player class, with a RectangleShape object as a private object, and I want to initialize it in the .cpp contstructor, but it doesn't work.我创建了播放器类,使用 RectangleShape 对象作为私有对象,我想在 .cpp 构造函数中初始化它,但它不起作用。

player.h:播放器.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);
};

And here is the player.cpp:这是 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.
}

You should use constructor initialiser list.您应该使用构造函数初始化列表。 For example like this;例如像这样;

Class definition类定义

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

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

Class implementation类实现

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

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

相关问题 如何在构造函数中初始化 C++ 对象成员变量? - How can I initialize C++ object member variables in the constructor? 如何使用给定构造函数的大小初始化 C++ 中的数组? - How can I initialize an array in C++ with a size that is given to the constructor? 无法使用C ++中的构造函数初始化对象 - Can`t initialize object using constructor in c++ 在C ++中的构造函数中初始化数组 - Initialize an array inside Constructor in C++ C++ 如何使用初始化/构造函数创建新的 object? - How does the C++ create new object with initialize/ constructor? C++ 在构造函数中初始化 object(多态) - C++ initialize object in constructor (polymorphic) 如何通过C ++中构造函数的初始化列表来值初始化类的私有结构成员? - how can I value initialize private struct member of class via initialization list of constructor in c++? 如何在C ++中的派生类的构造函数中初始化基类的const变量? - How can I initialize a const variable of a base class in a derived class' constructor in C++? c++ 如何在构造函数中初始化成员数组? - c++ How do I initialize a member array in a constructor? c ++如何在类对象内部初始化数组? - c++ How to initialize an array inside a class object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM