[英]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.