简体   繁体   中英

Const procedure in C++, weird error in Visual Studio C++ 2010?

class a{
public:
    int b;
    static int c;
    virtual void mod() const
    {
        c=4;
    }

};



int _tmain(int argc, _TCHAR* argv[])
{
  a bi;

  return 0;
}

Look at this... After compiling it using Visual Studio C++ 2010 compiler, I get...

cpplearningconsole.obj: error LNK2001: unresolved external symbol "public: static int a::c" (?c@a@@2HA)

I guess this is a compiler bug. For me, the real question is. Should mod be able to modify c variable if it is const?

Thanks.

You have just declared the static variable in the class definition, you need to define it in the by doing int a::c = 0;.

This:

cpplearningconsole.obj: error LNK2001: unresolved external symbol "public: static int a::c" (?c@a@@2HA)

Isn't a compiler message, it's a linker message. You're getting it, because although you have declared the member c , you haven't defined it. Static members need to be defined in only one source file, in order for them to be created. Something like:

int a::c = 0;

As for your second question, declaring a function as const , states that it doesn't modify the object that it's being called on. You mod function doesn't modify the object, it modifies the static member. Which is why you don't get a compiler error.

You should add the correct definition for your variable member, in the class you only have the declaration. In your cpp or just after the class declaration (outside of it) add:

int a::c = 0;

To answer your other question:

c is a public static member of your class. Anyone can change its value, so why not mod() ?

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