C++ C++;通过构造函数将类指针传递给另一个类
我有以下情况C++ C++;通过构造函数将类指针传递给另一个类,c++,oop,C++,Oop,我有以下情况 cpp文件: #include <Player.h> Ball::Ball(GLint x, GLint y, Player* bottomPlayer, Player* topPlayer) { this->x = x; this->y = y; } #include "Player.h" Player::Player(GLint windowWidth, GLint windowHeight, GLint playerLength) {
cpp
文件:
#include <Player.h>
Ball::Ball(GLint x, GLint y, Player* bottomPlayer, Player* topPlayer)
{
this->x = x;
this->y = y;
}
#include "Player.h"
Player::Player(GLint windowWidth, GLint windowHeight, GLint playerLength)
{
// initialization
}
另一个cpp
文件:
#include <Player.h>
Ball::Ball(GLint x, GLint y, Player* bottomPlayer, Player* topPlayer)
{
this->x = x;
this->y = y;
}
#include "Player.h"
Player::Player(GLint windowWidth, GLint windowHeight, GLint playerLength)
{
// initialization
}
我得到了以下错误:
调用“Player::Player()”时没有匹配的函数
我不知道这个错误意味着什么。。。为什么它认为我的构造函数是一个函数或类似的东西
为什么它认为我的构造函数是一个函数或类似的东西
因为构造函数是函数
我不知道这个错误意味着什么
这意味着您已尝试默认构造类Player
的实例,尽管该类不是默认可构造的。如果一个类没有默认构造函数,也就是说,它没有可以无参数调用的构造函数,那么它就不是默认可构造的
要解决此问题,请执行以下操作之一:
- 不要默认构造
Player
- 为
Player
这声明了一个播放器指针
bottomPlayer
和一个播放器实例(不是指针)topPlayer
。由于您没有在成员初始化列表中显式初始化topPlayer
,因此默认情况下初始化成员。这导致了错误。该错误意味着需要在代码中的某个地方调用Player
的默认构造函数,但您没有提供。除非你发布了一个命令,否则不可能知道如何修复。这些代码都不会调用Player
构造函数。所有Player
代码引用仅为指针。这个问题与您选择不发布的内容有关(我的crystal ball说它是ball
(或其他地方)类Player
中的一个成员变量,它不是使用您提供的唯一构造函数(三个参数)正确构造的)。该错误消息应该与发生的行号一起出现。@WhozCraig它指向球的构造函数Player*bottomPlayer,topPlayer代码>-Um<代码>顶层
不是指针;这是一个例子。变量前面缺少*
。孩子们,这就是为什么我们不把多个指针变量放在同一行上的原因。这是初学者常犯的错误。星号与变量相结合;不是类型(但可以通过别名与类型结合,这是您永远不应该做的;它只会使代码更难阅读)。理想情况下,你有Player*bottomPlayer;球员*顶级球员代码>在单独的行上。