将类代码分成头文件和 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;
}
相关文章