简体   繁体   中英

C++ static anonymous class type data member

I'm trying to write C# like property, so I got this:

#include <iostream>

class Timer
{
public:
    static class {
    public:
        operator int(){ return x;}
    private:
        int x;
    }y;
};
int main()
{
    std::cout << Timer::y;
    std::cin.get();
}

And finally I got this error:

error LNK2001: unresolved external symbol 
"public: static class Timer::<unnamed-type-y>y> Timer::y"

I would be appreciate if someone tells me why.

So it's only a declaration, that's too bad, can I get some way to make it a definition other than define y somewhere else or initialize it which I just don't like and can't do it without give the anonymous type a name.

You're getting this error because you have to define y somewhere, but you just declared it in the class definition. Declaring it can be tricky since it doesn't have any named type, and you have to specify the type when declaring it. But with C++11, you can use decltype to do so:

#include <iostream>

class Timer{
public:
    static class {
    public:
        operator int(){ return x;}
    private:
        int x;
    } y;
};

decltype(Timer::y) Timer::y;    //You define y here

int main(){
    std::cout << Timer::y;
    std::cin.get();
}

The simplest solution I can think of (although it introduces name for your unnamed class):

#include <iostream>

class Timer
{
private:
    class internal {
    public:
        operator int(){ return x;}
    private:
        int x;
    };

public:
    static internal y;
};

Timer::internal Timer::y;

int main()
{
    std::cout << Timer::y;
    std::cin.get();
}

Also, don't try to write anything "C#-like" in C++, it just doesn't work. And I don't see how static mix with C# property .

Edit: you can even mark the internal class as private , so the class itself won't be accessible from outside the class. See updated code.

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