我是C ++的新手,并且停留在声明类的语法上。
根据我收集到的信息,您应该将所有声明存储在头文件中,我将其称为clarifications.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;
}
};
Run Code Online (Sandbox Code Playgroud)
现在,播放器是一个类,我想将其存储在名为functions.cpp的cpp文件中
我想将上面的Player类移到下面的文件functions.cpp中
#include "common.h"
void incptr(int* value)
{
(*value)++;
}
void incref(int& value)
{
value++;
}
Run Code Online (Sandbox Code Playgroud)
common.h包含;
#pragma once
#include <iostream>
#include <string>
#include "declarations.h"
Run Code Online (Sandbox Code Playgroud)
我认为正在发生的事情是当我在头文件中编写Player类时,它已经在该文件中声明了。如果我将Player类移到functions.cpp中,则需要声明。我不确定编译器在涉及类时期望作为声明。
我试过了;
class Player();
functions::Player();
void Player::Move(int xa, int ya);
Run Code Online (Sandbox Code Playgroud)
还有其他一些变体,但对我来说最有意义。
很抱歉,如果这有点混乱,仍在尝试控制该语言。预先感谢您的帮助!
编辑:对不起,我错过了主要功能;
#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();
}
Run Code Online (Sandbox Code Playgroud)
类的声明就像
class Player; // Note there are no parentheses here.
Run Code Online (Sandbox Code Playgroud)
当您在两个类之间具有循环依赖关系时,最常使用这种形式。在头文件中定义类但将成员函数的定义放在.cpp文件中是更常见的。为了您的目的,我们可以制作一个名为的头文件player.h:
class Player
{
public:
int x, y;
int speed;
void Move(int xa, int ya);
void printinfo();
};
Run Code Online (Sandbox Code Playgroud)
请注意,此声明不包含成员函数的主体,因为它们实际上是定义。然后,您可以将函数定义放在另一个文件中。称呼它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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我们现在必须Player使用Player::语法将这些函数中的每一个指定为类的成员。
现在假设您main.cpp的main()函数中也有一个文件,则可以像这样编译代码:
g++ main.cpp player.cpp
Run Code Online (Sandbox Code Playgroud)
对于这个简单的示例,可以在类声明中定义函数。请注意,这会使函数“内联”,这是您应该阅读的另一主题。
| 归档时间: |
|
| 查看次数: |
735 次 |
| 最近记录: |