1

C++ では、クラスのオブジェクトを定義せずにクラスのデータ メンバーを使用できます。これstaticには、次のコード サンプルのように、パブリック セクションでそのデータ メンバーを変数として定義します。問題は、なぜ/いつこれをしたいのですか? どうすればそれを行うことができますか?

class ttime{
public:
    ttime(int h=0, int m=0, int s=0):hour(h), minute(m), second(s){}   //constructor with default intialization
    int& warning(){return hour;}
    void display()const{cout<<hour<<"\t";}
    static int hello; 
    ~ttime(){}

private:
    int hour;
    int minute;
    int second;
};


main()
{
    ttime:: hello=11310; //Is this the way to use hello without creating an object of the class?
    cout << ttime:: hello;

    ttime hi(9); 
    hi.display();
    hi.warning()++;//the user is able to modify your class's private data, which is really bad! You should not be doing this!
    hi.display();
}
4

5 に答える 5

0

これはグローバル変数に似ていますが、グローバル名前空間で定義されていないことだけが異なります。

名前空間が導入される前に記述された C++ コードや、より便利なテンプレート メタ プログラミングで見つけることができます。

一般に、あなたの例のように使用することはお勧めしません。グローバルな状態をできるだけ避けることをお勧めします。そうしないと、テストが困難なコードになってしまいます。

于 2015-02-11T18:47:35.747 に答える