How to implement static class member functions in *.cpp file?

前端 未结 8 1465
Happy的楠姐
Happy的楠姐 2020-12-07 15:35

Is it possible to implement static class member functions in *.cpp file instead of doing it in the header file ?

Are all static functions a

相关标签:
8条回答
  • 2020-12-07 15:58

    @crobar, you are right that there is a dearth of multi-file examples, so I decided to share the following in the hopes that it helps others:

    ::::::::::::::
    main.cpp
    ::::::::::::::
    
    #include <iostream>
    
    #include "UseSomething.h"
    #include "Something.h"
    
    int main()
    {
        UseSomething y;
        std::cout << y.getValue() << '\n';
    }
    
    ::::::::::::::
    Something.h
    ::::::::::::::
    
    #ifndef SOMETHING_H_
    #define SOMETHING_H_
    
    class Something
    {
    private:
        static int s_value;
    public:
        static int getValue() { return s_value; } // static member function
    };
    #endif
    
    ::::::::::::::
    Something.cpp
    ::::::::::::::
    
    #include "Something.h"
    
    int Something::s_value = 1; // initializer
    
    ::::::::::::::
    UseSomething.h
    ::::::::::::::
    
    #ifndef USESOMETHING_H_
    #define USESOMETHING_H_
    
    class UseSomething
    {
    public:
        int getValue();
    };
    
    #endif
    
    ::::::::::::::
    UseSomething.cpp
    ::::::::::::::
    
    #include "UseSomething.h"
    #include "Something.h"
    
    int UseSomething::getValue()
    {
        return(Something::getValue());
    }
    
    0 讨论(0)
  • 2020-12-07 16:04

    Sure You can. I'd say that You should.

    This article may be usefull:
    http://www.learncpp.com/cpp-tutorial/812-static-member-functions/

    0 讨论(0)
提交回复
热议问题