首页 > 解决方案 > 如何在 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;
    }
};

现在 Player 是一个类,我想将它存储在一个名为 functions.cpp 的 cpp 文件中

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

#include "common.h"

void incptr(int* value)
{
    (*value)++;
}

void incref(int& value)
{
    value++;
}

common.h 包含;

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

我认为正在发生的事情是当我在头文件中编写 Player 类时,它在该文件中声明,嗯,已经在那里了。如果我将 Player 类移动到 functions.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();
}

标签: c++

解决方案


一个类的声明就像

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.cpp文件main(),您可以像这样编译代码:

g++ main.cpp player.cpp

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


推荐阅读