如何在C++中声明类
How to declare a class in 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;
}
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
对于这个简单的示例,您将在类声明中定义函数。请注意,这使得函数"内联",这是您应该阅读的另一个主题。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别