How to use static variable in class with C++

2 Answers

0 votes
#include <iostream>

class Example {
    public:
        static int num;
        Example() {};
};
    
int Example::num = 23;

int main() {
    Example obj;
    
    std::cout << obj.num << "\n";
    
    int x = obj.num + 47;
    std::cout << x;
}
  
  
  
  
/*
run:
  
23
70
  
*/

 



answered Nov 27, 2022 by avibootz
0 votes
#include <iostream>
#include <cmath>

class Circle {
public:
    double r;
    static double pi; // static variable - one copy for all objects
    static double newArea(double r) { return M_PI * r * r; }
};

int main()
{
    double area = Circle::newArea(3);
    
    std::cout << area;
}



/*
run:

28.2743

*/

 



answered Dec 1, 2022 by avibootz

Related questions

2 answers 228 views
1 answer 193 views
193 views asked Jul 18, 2014 by avibootz
1 answer 202 views
1 answer 109 views
1 answer 100 views
1 answer 101 views
...