在C++中使用类来存储和列出变量/方法是一种好习惯

Asp*_*bie 0 c++ oop class

我最近开始在编程中使用类,特别是在这种情况下使用C++,我试图理解实际使用它们的理想方法.理想情况下,如果确实存在这样的标准,我希望养成练习写出行业期望的习惯.我知道你可以使用类来保存对象有用的特定信息,例如汽车类.但是,诸如'Formulas()'这样的类只能存储程序其余部分可以使用的方法,或者只有一个变量类来保存​​常量,全局变量,或者只是你希望其他程序访问的任何东西.

int main()
{
    //Just used minimally to start the program
}


class Car()
{
    //Variables of a car: Model, year etc
    //Methods of a car: Such as drive(), parkUp(); refuel(); 
}

//Below here is class formalities I'm unsure about, are they okay to use this way
class Formulas()
{
    //holds a bunch of a formulas/methods almost all the classes can utilize
    //Examples below
    void ErrorCheck()
    {
        //checks input errors
    }
    void ColourChange()
    {
        //changes font colour
    }
    void Clear()
    {
        //clears screen
    }
}

//A class to hold variables for the rest of the program
class VariableList()
{
    //store CONST_VARIABLES here

    //store global_variables here

    //other variables
}
Run Code Online (Sandbox Code Playgroud)

总而言之,这是一种使用类,不实用,可怕等的公平方式.

任何类型的见解将不胜感激.我在发布之前尝试过调查这个问题,但是找不到源代码或解释信息以获得我想要的答案.感谢您阅读此内容,如果有任何我可以添加的内容,请告诉我们.

Fra*_*fer 7

类通常只对封装数据和使用对此数据进行操作的函数进行分组才有意义.如果您只想对不对相同数据进行操作的许多相关函数进行分组,则命名空间而不是类就足够了.

在你的情况下它可以看起来像这样:

namespace formulas
{
    void ErrorCheck()
    {
        //checks input errors
    }
    void ColourChange()
    {
        //changes font colour
    }
    void Clear()
    {
        //clears screen
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以调用这些函数:

formulas::ErrorCheck();
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你的功能似乎并没有真正相关,但我想这不是重点.