首页 > 解决方案 > C ++通过构造函数将类指针传递给另一个类

问题描述

我有以下情况

cpp文件:

#include <Player.h>
Ball::Ball(GLint x, GLint y, Player* bottomPlayer, Player* topPlayer)
{
    this->x = x;
    this->y = y;
}

头文件:

class Ball
{
    public:
        Ball(GLint x, GLint y, Player* bottomPlayer, Player* topPlayer);
    private:
        Player* bottomPlayer, topPlayer;
}

另一个cpp文件:

#include "Player.h"
Player::Player(GLint windowWidth, GLint windowHeight, GLint playerLength)
{
  // initialization
}

我收到以下错误:

没有调用“Player::Player()”的匹配函数

我不知道这个错误是什么意思......为什么认为我的构造函数是一个函数或类似的东西......

标签: c++oop

解决方案


为什么它认为我的构造函数是一个函数或类似的东西......

因为构造函数是函数。

我不知道这个错误是什么意思......

这意味着您尝试默认构造类的实例,Player尽管该类不是默认可构造的。一个类不是默认可构造的,如果它没有默认构造函数,即它没有可以不带参数调用的构造函数。

要修复它:

  • 不要默认构造Player
  • 定义一个默认构造函数Player
private:
    Player* bottomPlayer, topPlayer;

这声明了一个播放器指针bottomPlayer和一个播放器实例(不是指针)topPlayer。由于您没有topPlayer在成员初始化列表中显式初始化,因此您默认初始化该成员。这会导致错误。


推荐阅读