質問

Is it possible to make a class which does not need to be instantiated? In other words, is it possible to use functions of that class without having an instance of it?

役に立ちましたか?

解決 2

You could make all member functions and variables static, but then one starts to wonder why it should be a class, and not a namespace.

There is a good reason, though: you may want to use a class template like this. C++14 will add variable templates, which make the same possible without a class. A class also allows access control; you can fake this for the non-template case with anonymous namespaces, but a class may be more natural.

他のヒント

You can use static functions, those are bound to the Class, not an instance.

class Test{
    static void 
    doSomething()
    {
        std::cout << "something" << std::endl;
    }
}

int
main(int argc, char** argv)
{
    Test::doSomething(); //prints "something" without instance of Test
}

Otherwise you could build a Singleton, in which case the class itself would hold the instance, but I am not sure if this is what you wanted to know...

A static method can be called without creating an instance of the class.

class CMyClass
{
    public:
    static void Method1()
    {
        printf("Method1\n");
    }
};

CMyClass::Method1();    // Prints "Method1".

Yes, it is possible. If you want to use of class without having instance of it, you must use static functions.

You can also create private constructor of such class with static methods to prevent from creating any instances

For that you should use the static modifier. See documentation here: http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top