简体   繁体   中英

How to implement static classes in c++?

I was wanting to implement a simple static class that calculates the pow value of an integer in c++ while practicing. So my codes here:

#pragma once
#ifndef MATH_H
#define MATH_H
static class Math
{
    public:
        static int pow(int,int);
};


#endif /* MATH_H */

And the implemetation of pow function:

#include "Math.h"

int Math::pow(int base, int exp){
    if(exp==1)
        return base;
    else if(exp%2==0)
        return pow(base,exp/2)*pow(base,exp/2);
    else
        return pow(base,exp/2)*pow(base,exp/2)*base;
}

But the cygwin compiler is throwing compilation error:

In file included from Math.cpp:16:0:
Math.h:16:1: error: a storage class can only be specified for objects and functions
 static class Math
 ^~~~~~

Please help me solve my problem. 这是Microsoft课程的官方文档,我从中学到了c ++中有静态类

C++ does not have "static classes" as they formally exist in other languages. You can, however, delete the default constructor (C++ >= 11) or make it private and unimplemented (C++ < 11) which has the same effect of making the type not constructible:

// C++ >= 11
class Math
{
public:
    Math() = delete;
};

// C++ < 11
class Math
{
private:
    Math(); // leave unimplemented
};

With this code, the line Math m; will fail:

(C++ >= 11) error: use of deleted function 'Math::Math()'

(C++ < 11) error: 'Math::Math()' is private within this context

However, "static classes" are mostly an anti-pattern in C++ and free functions should be preferred. (There are some cases where static classes can be useful, particularly when doing template metaprogramming. If you're not doing that then you almost certainly don't need a static class.)

Consider instead declaring the functions in a namespace:

namespace math {
    int pow(int, int);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM