如何在C++中声明类

How to declare a class in C++

本文关键字:声明 C++      更新时间:2023-10-16

我是 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;
}
void printinfo()
{
std::cout << x << y << speed << std::endl;
}
};

现在播放器是一个类,我想存储在一个名为函数的 cpp 文件中.cpp

我想将上面的 Player 类移动到下面的文件函数中.cpp

#include "common.h"
void incptr(int* value)
{
(*value)++;
}
void incref(int& value)
{
value++;
}

共同.h 包含;

#pragma once
#include <iostream>
#include <string>
#include "declarations.h"

我认为正在发生的事情是,当我在头文件中编写 Player 类时,它已经在该文件中声明,嗯,已经存在了。如果我将 Player 类移动到函数中.cpp我需要留下一个声明。我不确定编译器在涉及类时期望什么作为声明。

我试过了;

class Player();
functions::Player();
void Player::Move(int xa, int ya);

还有一些其他的变化,但这些对我来说最有意义。

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

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

#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;
}

请注意,我们现在必须如何指定这些函数中的每一个都是具有Player::语法的Player类的成员。

现在假设你还有一个包含main()函数的main.cpp文件,你可以像这样编译你的代码:

g++ main.cpp player.cpp

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