c++ - 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()”的匹配函数
我不知道这个错误是什么意思......为什么认为我的构造函数是一个函数或类似的东西......
解决方案
为什么它认为我的构造函数是一个函数或类似的东西......
因为构造函数是函数。
我不知道这个错误是什么意思......
这意味着您尝试默认构造类的实例,Player
尽管该类不是默认可构造的。一个类不是默认可构造的,如果它没有默认构造函数,即它没有可以不带参数调用的构造函数。
要修复它:
- 不要默认构造
Player
- 定义一个默认构造函数
Player
private: Player* bottomPlayer, topPlayer;
这声明了一个播放器指针bottomPlayer
和一个播放器实例(不是指针)topPlayer
。由于您没有topPlayer
在成员初始化列表中显式初始化,因此您默认初始化该成员。这会导致错误。
推荐阅读
- perl - 为什么这个程序读取文件会导致死循环?
- ruby - 使用 brew 在 mac 中安装 nvm 时出错
- javascript - 用另一种方式而不是按钮提交 Rails 表单
- android - 如何使 com.google.android.material.button.MaterialButton 文本小写
- java - Base64 编码 .rtf 和 .pdf 类型文件 - Java/Groovy
- c# - ASP .NET Core 2.1 React 模板不能与控制器对话?
- r - Webscraping R 脚本不能从 crontab 运行
- python - 无法调试列表索引超出范围错误
- laravel-5 - 在 laravel 中添加自定义 css/js 文件
- vb.net - 在文本字段上添加签名 - itextsharp