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的头文件,并且看到许多类方法都以完全相同的方式组织。为什么会这样?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)