如何在C++; 我是C++的新手,我坚持声明类的语法。

如何在C++; 我是C++的新手,我坚持声明类的语法。,c++,C++,根据我收集的信息,您应该将所有声明存储在头文件中,我称之为declarations.h #pragma once void incptr(int* value); void incref(int& value); class Player { public: int x, y; int speed; void Move(int xa, int ya) { x += xa * speed; y += ya * speed

根据我收集的信息,您应该将所有声明存储在头文件中,我称之为declarations.h

#pragma once

void incptr(int* value);
void incref(int& value);

class Player
{
public:
    int x, y;
    int speed;

    void Move(int xa, int ya)
    {
        x += xa * speed;
        y += ya * speed;
    }

    void printinfo()
    {
        std::cout << x << y << speed << std::endl;
    }
};
普通。h包含

#pragma once
#include <iostream>
#include <string>
#include "declarations.h"
还有一些其他的变化,但这些对我来说最有意义

抱歉,如果这有点混乱,仍在尝试掌握语言。提前感谢您的帮助

编辑:对不起,我错过了主要功能

#include "common.h"



int main()
{   

    Player player = Player();
    player.x = 5;
    player.y = 6;
    player.speed = 2;
    player.Move(5, 5);
    player.printinfo();

    std::cin.get();
}

类的声明与

class Player; // Note there are no parentheses here.
当两个类之间存在循环依赖关系时,最常用此表单。通常在头文件中定义类,但将成员函数的定义放在.cpp文件中。出于您的目的,我们可以创建一个名为
player.h
的头文件:

class Player
{
public:
    int x, y;
    int speed;

    void Move(int xa, int ya);
    void printinfo();
};
请注意,此声明不包含成员函数的主体,因为它们实际上是定义。然后可以将函数定义放入另一个文件中。称之为player.cpp

void Player::Move(int xa, int ya)
{
    x += xa * speed;
    y += ya * speed;
}

void Player::printinfo()
{
    std::cout << x << y << speed << std::endl;
}

对于这个简单的示例,您可以在类声明中定义函数。请注意,这会使函数“内联”,这是您应该阅读的另一个主题。

当我将类播放器移动到functions.cpp中时,错误发生在哪里。目前代码运行正常。但是在头文件中有一个完整的类感觉有点恶心
类播放器?,然后在其他地方定义函数。。。此外,头文件和cpp文件必须具有相同的名称。。。类似于player.h和player.cpp,而不是declarations.h和functions.cpp(完全不同的名称…),我仍然觉得很奇怪,一个类必须在一个文件中声明,在另一个文件中定义。这就把它弄清楚了,只是需要一些练习。非常感谢。我让它运行起来了。它可能也在同一个文件中定义和声明。
class Player
{
public:
    int x, y;
    int speed;

    void Move(int xa, int ya);
    void printinfo();
};
void Player::Move(int xa, int ya)
{
    x += xa * speed;
    y += ya * speed;
}

void Player::printinfo()
{
    std::cout << x << y << speed << std::endl;
}
g++ main.cpp player.cpp