简体   繁体   English

C ++静态匿名类类型数据成员

[英]C++ static anonymous class type data member

I'm trying to write C# like property, so I got this: 我正在尝试像属性一样编写C#,所以我得到了:

#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. 因此,这只是一个声明,这太糟糕了,除了在其他地方定义y或初始化它(我只是不喜欢而且不能不给匿名类型命名而无法做到)之外,我是否可以得到某种使它成为定义的方法。

You're getting this error because you have to define y somewhere, but you just declared it in the class definition. 之所以收到此错误,是因为您必须在某处定义y ,但您只是在类定义中声明了它。 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: 但是对于C ++ 11,您可以使用decltype来做到这一点:

#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. 另外,不要尝试在C ++中编写任何类似“ C#的东西”的东西,这只是行不通的。 And I don't see how static mix with C# property . 而且我看不到static如何与C# property混合。

Edit: you can even mark the internal class as private , so the class itself won't be accessible from outside the class. 编辑:您甚至可以将internal类标记为private ,因此无法从类外部访问该类本身。 See updated code. 查看更新的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM