开发者

static member explicit definition

开发者 https://www.devze.com 2023-03-19 14:29 出处:网络
Consider this code: #include<iostream> using namespace std; class Wilma { public: static int i; Wilma()

Consider this code:

#include<iostream>
using namespace std;
class Wilma
{
    public:
        static int i;
        Wilma()
        {
            cout<<"\nWilma ctor\n";
            cout<<"\ni::"<<i<<"\n";
        }
};
class Fred
{
    public:
        Fred()
        {
            cout<<"\nFred ctor\n";

        }
        static Wilma wilma_;
};
int Wilma::i=44;//------------- LINE A
int main()
{
    int a=0;
    Wilma::i=a;//---------- LINE C
    Wilma w;
    Fred::wilma_=w;//---------- LINE B

}

here line A explicitly defines the static int a of Wilma class.(commented out to cause linker error) and with开发者_JS百科out which the linker gives undefined reference error.(because Wilma::i is actually being used,if i dont use it no linker errors are there.)

Same should be true for static Wilma wilma_ of Fred class,i.e it should be explicitly defined aswell..because it is also being used in the code at line B. But thats not the case,no linker errors for Fred::wilma_ if its not been explicitly defined. why? Tested on gcc 4.5.2

EDIT: I somehow got another doubt about this...

LINE C and LINE B both are trying to use static objects of a class,int Wilma::i and Wilma Fred::wilma_ respectively. But only a definition for int Wilma::i is mandatory?

Why isnt Wilma Fred::wilma_; mandatory?

I understand the answer that the line B is a no-op. but same can be said about line C too??


Wilma has no non-static fields. Fred::wilma_=w; doesn't do anything.

edit

If there are no non-static members - there's no copy. Basically the assignment was a no-op and might just been optimized out by the compiler, and the linker never saw it. Adding a non-static member made the copy to be an actual operation that referenced the static variable, thus the compiler couldn't optimize it out and the linker saw it.


You declared static int i; in Wilma, but never defined it. So by adding back in Line A, it will cause Wilma::i to be defined, which is what the compiler is complaining about. So you have to define it somewhere outside the class and not inside main.

Finally, the Fred and Wilma classes are essentially empty (aside from a ctor and static class member). There is nothing to copy between them.

Edit: Based on the comments to @littleadv, you have to have an identical class if you are going to perform a copy. If you put an int j in the Wilma class but nothing in the Fred class, then it won't work because where should it put j in the Fred class?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号