3

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.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99

2 Answers2

1

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.

Griwes
  • 8,805
  • 2
  • 43
  • 70
  • 1
    @Mike, well, proxy objects are fine, but you can easily name that class. Unnamed types are Evil (tm). – Griwes Apr 16 '12 at 11:34
1

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();
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99