【问题标题】:c++ using a class object as a class memberc++ 使用类对象作为类成员
【发布时间】:2020-02-27 23:38:41
【问题描述】:

“cludes.h”是一个头文件,我把我所有的头文件和命名空间都放进去。

hit_box.h

#include "cludes.h"
class hit_box{
    friend class player;
private:
    /*class members*/
public:
    // without this I get "no default constructor" error. 
    hit_box(); 
    //I think having two constructors will create problems but that's a problem on top of my current problem 

    hit_box(char typ, int t, int x, int y, float Px, float Py,int pw, float spotx, float spoty);
}

player.h

    #pragma once
#include "cludes.h"

class player {
public:
    enum states { falling, hurt, landed, jumping };
    player(float a, float b, int f, sf::Texture t, sf::Texture t2, hit_box pnch);
private:
    //other class members
    hit_box punch;
}

player.cpp

#include "player.h"
#include "cludes.h"
player::player(float a, float b, int f, sf::Texture t, sf::Texture t2, hit_box pnch){
    /*other class members*/
    hit_box punch = pnch;
}

我希望hit_box 成为我可以在播放器类函数中调用的成员。 这些是我收到的错误消息

Error C2061    syntax error: identifier 'hit_box' 
Error C3646    'punch': unknown override specifier
Error C4430    missing type specifier - int assumed. Note: C++ does not support default-int

我尝试通过

继承hit_box类

player.h

#include "cludes.h"
class player {
    hit_box punch;
public:
player(float a, float b, int f, sf::Texture t, sf::Texture t2);
}

player.cpp

#include "player.h"
#include "cludes.h"
player::player(float a, float b, int f, sf::Texture t, sf::Texture t2) : punch('!', 10, 30, 64, -10, -10, 20, 4.44, 4.44){
//other class members
}

这种方式没有hit_box 默认构造函数,只有非默认构造函数。 不管我还是得到

Error C3646    'punch': unknown override specifier
Error C4430    missing type specifier - int assumed. Note: C++ does not support default-int

如果这是重要信息,我正在使用 sfml。

【问题讨论】:

  • 这是您要编译的实际代码吗?至少,每个类定义后都缺少分号。

标签: c++ visual-c++ sfml


【解决方案1】:

您在 hit_box.h 中定义了 hit_box,但没有任何文件使用它 #include <hit_box.h>。编译该代码时,编译器不知道 hit_box 是什么。

添加到您的 player.h 文件中

#include "cludes.h"
#include "hit_box.h"
class player {

“'cludes.h”是一个头文件,我把我所有的头文件和命名空间都放进去。”

如果includes.h #includes你的其他头文件,你有循环依赖,你需要forward declare.

【讨论】:

  • 感谢您的帮助。对于任何处理我的问题的人,最好只继承该类,而不是采取懒惰的捷径,例如将所有头文件放在一个文件中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2021-01-12
  • 1970-01-01
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多