I seem to have some misconceptions about `static` in C++ -
i seem have misconceptions how static
keyword works in c++; specifically, need understand problem following code:
#include <iostream> struct a{ int a; a(int ain) : a(ain) { } a() : a(1) { } static geta() { return a(2); } }; struct b { static a = a::geta(); }; int main() { std::cout << b::a.a << std::endl; }
had static
worked expected to, above code sample have printed 2
, exited - instead, following compiler error message:
g++ -c -o syntax.o syntax.cpp syntax.cpp:17:21: error: ‘a::geta()’ cannot appear in constant-expression static a = a::geta(); ^ syntax.cpp:17:26: error: function call cannot appear in constant-expression static a = a::geta(); ^ syntax.cpp:17:26: error: invalid in-class initialization of static data member of non-integral type ‘a’ syntax.cpp:17:26: error: initializer invalid static member constructor syntax.cpp:17:26: error: (an out of class initialization required) syntax.cpp:17:26: error: ‘b::a’ cannot initialized non-constant expression when being declared make: *** [syntax.o] error 1
i read error messages , realize there's static
haven't understood, find hard pinpoint what. it's because i've done fair amount of work in languages java , c#, have static
keyword it, apparently, works differently.
will please explain me why above code invalid?
static member functions
there 2 ways of invoking static member function of given t
, either;
you use scope resolution operator
::
, or;you invoke on instance of said type
t
usingoperator.
(as if invoking other member-function on variable).
legal constructs
struct obj { static void func () { /* ... */ } };
the 2 snippets below both call static member function func
within obj
.
obj a; a.func ();
obj::func ();
illegal constructs
obj a; obj.func (); // illegal, `obj` type , not instance ::func (); // illegal, `a` instance of `obj`, not type
static data members
static
data members used declare variables shared between every instance of given type.
in snippet provided in question trying initialize static data member a
of type a
returned value from, corrected, a::geta ()
. not allowed since trying initialize static
data member without making constexpr
illegal construct in-class initialization.
struct b { static a = a::geta(); // illegal, `static a` not `constexpr` };
more in-class initialization of static data members can found here:
Comments
Post a Comment