0

So I'm building a Regex class, with a simple constructor:

regex.hpp

#ifndef REGEX_CUSTOM_CLASS
#define REGEX_CUSTOM_CLASS

#include <stdio.h>

using namespace std;

class Regex
{
private:
    /* data */
public:
    char *regex;

    Regex(char str[]);
};

#endif  // REGEX_CUSTOM_CLASS

regex.cpp

#include <iostream>
#include <list>
#include <assert.h>
#include <ctype.h>
#include <stdio.h>

#include "regex.hpp"

using namespace std;


Regex::Regex(char str[])
{
    regex = str;
}

tools.cpp

#include <iostream>
#include <stdio.h>

#include "lib/regex/regex.cpp"

using namespace std;

int main() {
    Regex my_regex("//");

    cout << my_regex.regex << endl;

    return 0;
}

But after I compile it to .exe file and run it, I get this error message: warning: ISO C++ forbids converting a string constant to 'char*' Regex my_regex("//");

I think the problem is with the data types. What is the problem?

  • The error message is correct to use `"//"` you need have the functiin gave a `const char*` parameter. – drescherjm Nov 27 '20 at 18:44
  • @WebTools -- The `"\\"` is not a `char *`. It is a `const char *`. – PaulMcKenzie Nov 27 '20 at 18:52
  • 1
    A note on the duplicate: The message has changed a bit and the result is now a hard error instead of the warning used to let people know that the transition to making it an error was underway, but the mechanics are the same. – user4581301 Nov 27 '20 at 18:59

1 Answers1

1

You cannot pass arrays by value. When you write:

Regex::Regex(char str[])

this actually is

Regex::Regex(char* str)

Moreover string literals are of type const char [N] (where N is length of the string including the null terminator) and when passed to functions they decay to const char*. Getting a char* from a const char* (pointer to constant char, not to be confused with constant pointer to char) would break const correctness.

Either use std::string as argument type or change it to const char*.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185