静态矢量的Getter
Getter for static vector
我有一个可以工作的类。但当我为它添加静态向量和getter时,我遇到了编译错误。
这里有一个例子:
// Config.h file
class Config {
static std::vector<std::string> m_RemoteVideoUrls;
...
public:
static std::vector<std::string> GetRemoteVideoURLs();
};
// Config.cpp file
static std::vector<std::string> m_RemoteVideoUrls = {"some url"};
...
std::vector<std::string> Config::GetRemoteVideoURLs() {
return m_RemoteVideoUrls;
}
我在Visual Studio 2017 中编译时遇到了这个奇怪的错误
1>config.obj : error LNK2001: unresolved external symbol "private: static class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > Config::m_RemoteVideoUrls" (?m_RemoteVideoUrls@Config@@0V?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@A)
经过几次实验,我明白我的m_RemoteVideoUrls
出了问题。因为这个存根有效:
std::vector<std::string> Config::GetRemoteVideoURLs() {
return std::vector<std::string>{"a", "b"};// m_RemoteVideoUrls;
}
但这不起作用:
std::vector<std::string> Config::GetRemoteVideoURLs() {
LoadConfigIfRequired();
std::vector<std::string> tmp = m_RemoteVideoUrls;
return std::vector<std::string>{"a", "b"};// m_RemoteVideoUrls;
}
怎么了?
static std::vector<std::string> m_RemoteVideoUrls = {"some url"};
只是一个不相关的全局变量,要给静态成员下定义,它应该是
std::vector<std::string> Config::m_RemoteVideoUrls = {"some url"};
您声明了一个与静态向量同名的全局向量,但静态向量本身从未定义。有必要指定矢量所属的位置(指定范围(:
static std::vector<std::string> Config::m_RemoteVideoUrls = {"some url"};
// ^^^^^^^^
实际上,你甚至可以同时拥有两个矢量:
static std::vector<std::string> m_RemoteVideoUrls = {"some url"};
static std::vector<std::string> Config::m_RemoteVideoUrls = {"another url"};
什么时候使用哪一个?好吧,这取决于您所处的范围:Config类的成员函数使用静态成员,其他类的成员和全局函数使用全局成员(除非您明确指定范围:::m_RVU
与Config::m_RVU
(。
当然,拥有相同的名字不是一个好主意,这只是为了说明。。。
然后是第二个问题:
你真的打算按值返回静态成员吗(例如,一直复制一个(?
您可能更喜欢返回一个参考:
public:
static std::vector<std::string> const& getRemoteVideoURLs();
// ^^^^^^
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- #为""定义宏;静态";针对不同的上下文
- cmake如何在fedora工作站中找到boost静态库包
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- cmake在我的项目中所需的所有静态库都不成功
- C++从另一个类访问公共静态向量的正确方法是什么
- 基于boost的程序的静态链接——zlib问题
- 在静态库中嵌入类方法
- 如何通过 getter 函数删除矢量的元素?
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 如何在C++中获得"静态纯虚拟"功能?
- 私有类型的静态常量成员
- 使用gcc从静态链接的文件中查找可选符号
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 静态矢量的Getter
- 纯标头库中静态成员变量的正确设置器和 getter
- 如何使用静态变量,使用自定义Getter和设置器在SWIG中扩展结构
- c++如何构建静态私有成员的getter
- 使用const getter风格的函数代替静态数据成员