首页 > 解决方案 > (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 的头文件,我看到许多类方法以相同的方式组织。为什么是这样?

标签: c++classlayoutconventionsdeclare

解决方案


推荐阅读