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

3

我正在尝试编写类似于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();
}

最后我遇到了这个错误:

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

我希望有人能告诉我为什么。
所以这只是一个声明,太糟糕了,我能不能找到一些方法让它成为一个定义,而不是在其他地方定义y或初始化它,这是我不喜欢并且不能给匿名类型命名的。

1
你必须在某个地方定义y(而不仅仅是声明)。 - Vaughn Cato
https://dev59.com/V3VC5IYBdhLWcg3wvT_g - Vaughn Cato
2个回答

1
您会收到此错误是因为您需要在某个地方定义y,但是您只是在类定义中声明了它。声明它可能有些棘手,因为它没有任何命名类型,并且您必须在声明时指定类型。但是在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();
}

1
我能想到的最简单的解决方案(尽管它为您的未命名类引入了名称)是:
#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();
}

此外,不要试图在C++中编写任何类似于C#的代码,这是行不通的。我也不知道如何将static与C#的property混合使用。

编辑:您甚至可以将internal类标记为private,这样该类本身就无法从类外部访问。请参见更新后的代码。


1
@Mike,代理对象没问题,但你可以轻松地命名该类。未命名类型是邪恶的(商标)。 - Griwes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接