将类代码分成头文件和 cpp 文件 [英] Separating class code into a header and cpp file

查看:35
本文介绍了将类代码分成头文件和 cpp 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑如何将一个简单类的实现和声明代码分离到一个新的头文件和 cpp 文件中.例如,我将如何分离以下类的代码?

I am confused on how to separate implementation and declarations code of a simple class into a new header and cpp file. For example, how would I separate the code for the following class?

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y)
  {
    gx = x;
    gy = y;
  }

  int getSum()
  {
    return gx + gy;
  }
};

推荐答案

类声明进入头文件.添加 #ifndef 包含保护很重要.大多数编译器现在还支持 #pragma once.我也省略了私有,默认情况下 C++ 类成员是私有的.

The class declaration goes into the header file. It is important that you add the #ifndef include guards. Most compilers now also support #pragma once. Also I have omitted the private, by default C++ class members are private.

// A2DD.h
#ifndef A2DD_H
#define A2DD_H

class A2DD
{
  int gx;
  int gy;

public:
  A2DD(int x,int y);
  int getSum();

};

#endif

并且实现在 CPP 文件中:

and the implementation goes in the CPP file:

// A2DD.cpp
#include "A2DD.h"

A2DD::A2DD(int x,int y)
{
  gx = x;
  gy = y;
}

int A2DD::getSum()
{
  return gx + gy;
}

 

这篇关于将类代码分成头文件和 cpp 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆