如何将 std::regex 对象定义为类中的 const 静态成员并在函数中使用它?

问题描述

我有

class C
{
  private:
    const static std::regex r;
}

我想给变量 r 一些要解析的字符串,例如:

//ATTENTION: IT'S NOT CORRECT,HOW TO DEFINED IT CORRECTLY?
std::regex r("Hello\n");

我在同一个类中有一个函数我有多个 if 语句来检查字符串是否被解析

if(std::regex_match(user_input,r)
{
  std::cout << "match";
}
else
{
  std::cout << "no match";
}

当 r 尚未定义时,如何正确使用 r 并将 user_input 与 r 进行比较?

解决方法

像这样:

// === header file c.h ===
#ifndef C_H
#define C_H
#include <regex>
class C
{
private:
   const static std::regex r;
};
#endif

// === source file c.cpp ===
#include "c.h"
const std::regex C::r{"Hello\n"};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...