簡體   English   中英

C ++靜態匿名類類型數據成員

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

我正在嘗試像屬性一樣編寫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或初始化它(我只是不喜歡而且不能不給匿名類型命名而無法做到)之外,我是否可以得到某種使它成為定義的方法。

之所以收到此錯誤,是因為您必須在某處定義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();
}

我能想到的最簡單的解決方案(盡管它為您的未命名類引入了名稱):

#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 ,因此無法從類外部訪問該類本身。 查看更新的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM