c++ - (C++) 当我被教导分离声明和实现时,为什么我看到一些程序员用类来做这件事?
问题描述
我看到了这段代码,它可以编译。这并不奇怪,但为什么它是这样组织的呢?为什么没有class.cpp
?(编辑:我的意思不是空格,我的意思是位置。)
/// main.cpp ///
#include <iostream>
#include "class.h"
int main() {
Pet a(4);
double x;
std::cout << "How much does this weigh? "; std::cin >> x;
Pet b(x);
Pet c(b);
std::cout << "You have " << a.getTotal() << " pets." << std::endl;
std::cout << "a weighs " << a.getWeight() << " pounds." << std::endl;
std::cout << "b weighs " << b.getWeight() << " pounds." << std::endl;
std::cout << "c weighs " << c.getWeight() << " pounds." << std::endl;
return 0;
}
/// class.h ///
#ifndef CLASS_H_
#define CLASS_H_
class Pet {
private:
double weight;
static int total;
public:
Pet() { weight = 0; upTotal(); }
Pet(double w) { weight = w; upTotal(); }
Pet(const Pet& that) { this->weight = that.weight; upTotal(); }
double getWeight() { return weight; }
void setWeight (double w) { weight = w; }
int getTotal() { return total; }
void upTotal() { ++total; }
void downTotal() { --total; }
};
int Pet::total = 0;
#endif // CLASS_H_
有人告诉我,将类声明分离到头文件中并将其内部留作源文件是一种很好的做法。但是这里这些函数是在头文件中定义的,而不是仅仅被声明。
在那之后我并没有想太多,直到我查看了一个属于 GUI IDE 的头文件,我看到许多类方法以相同的方式组织。为什么是这样?
解决方案
推荐阅读
- python - 如何知道 Django 中 FileField 中文件路径的长度?
- javascript - 有没有办法知道函数的返回值类型而不执行它?
- excel - excel - 除每个数字
- ios - XCode 代码设计问题
- angular - 在 redux-observable 史诗中的所有动作之后触发一个动作
- android - 程序类型已存在
- leaflet - Vaadin:v-leaflet-editable:PolygonField:重绘多边形
- three.js - ThreeJS 顶点绘制全三角形
- c# - 使用 EntityFramework 的结果分页列表
- facebook - 将 alexa 与 facebook 连接的问题