[英]How to initialize a private static set in c++?
我有一個帶有以下標頭聲明的私有集成員
class foo
{
private:
static std::set<int> _mySet;
};
如何在我的源文件中使用 _mySet? 我試圖初始化它,但這些沒有用:
std::set<int> foo::_mySet{}; // error: qualified-id in declaration before ‘{’ token
foo::_mySet = std::set<int>(); // error "...is private within this context"
這在 VS2017 CE 中編譯得很好
foo.h
#pragma once
#include <set>
class Foo {
private:
static std::set<int> mySet_;
public:
Foo() = default;
static std::set<int> getSet() {
return mySet_;
}
static void addToSet( int val ) {
mySet_.insert( val );
}
};
文件
#include "Foo.h"
std::set<int> Foo::mySet_{};
如果您嘗試這樣做:
static std::set<int> mySet_ = {};
// or
static std::set<int> mySet_{};
在頭文件中,Visual Studio 建議a member with an in-class initializer must be const
所以如果我們把它改成const
static const std::set<int> mySet_ = {};
// or
static const std::set<int> mySet{};
Visual Studio 抱怨a member of type "const std::set<int, std::less<int>, std::allocator<int>>" cannot have an in-class initializer
我希望這有助於澄清編譯器如何解釋這些聲明 - 定義和初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.