假设我正在上课
#include<iostream>
#include<string>
template<typename CharT>
class base
{
//.....
public:
using string_type = std::basic_string<CharT>;
static inline string_type var;
//.....
};
class derived : public base<char>
{
private:
using base<char>::var;
public:
static base<char>::string_type get()
{
return var;
}
};
//template<>
//base<char>::string_type base<char>::var = "Value";
int main()
{
std::cout << derived::get();
}
base
类接受 char
类型并为该类创建一个字符串类型,但我想在类中使用该 strng_type
字符串, 所以我创建了一个必须由类的用户设置的 static string_type
变量。
char
的值为 "Value"
,wchar_t
的值为 L"Value"
。所以我想通过继承指定类型 (char
) 的类来对用户隐藏 var
现在如何初始化 var
。
我已经尝试通过删除 inline
并取消注释它工作的模板,但是有一种方法可以初始化 inline static
基类变量。
- 如何初始化基类内联静态数据成员?
- 这样做是个好主意吗?
最佳答案
How to init base class inline static data member?
删除内联
,你应该是able to initialize the var
template<typename CharT>
class base
{
public:
using string_type = std::basic_string<CharT>;
static string_type var;
// ^^^^^^^^^^^^^^^^^^^
};
template<>
base<char>::string_type base<char>::var = "Value";
template<>
base<wchar_t>::string_type base<wchar_t>::var = L"Value";
It is a good idea doing like this?
不确定设计。因为你在这里提到的
"I want to hide the
var
from a user by inheriting the class in specified type(char
) [...]"
看起来,还是可以通过
std::cout << base<char>::var;
关于c++ - 如何在派生类中初始化基类静态内联数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63223162/