0

I have defined this function in my header of the class ContextFreeGrammar:

friend ContextFreeGrammar & operator<<(ContextFreeGrammar & cfg, string toRead);

and it is implemented in the cpp file as :

ContextFreeGrammar & operator<<(ContextFreeGrammar & cfg, string toRead)
{

  if (toRead[0] == 'I')
  {
    string parsedNameOfVariable = Variable::parseLabel(toRead.substr(1, toRead.length() - 1));
    cfg.setInitialVariable(Variable(parsedNameOfVariable));
    return cfg;
}


  Rule newRule = Rule::parseLabel(toRead);

  cfg.addRule(newRule);

  return cfg;
}

however in the main() when I create this object and initalize it (ContextFreeGrammar.h is imported) :

    ContextFreeGrammar cfg;

        cfg << "{A}->{B}"
            << "{B}->{C}"
            << "{C}->{D}"
            << "{D}->a{N}"
            << "{B}->c";

I get this error :|undefined reference to `operator<<(ContextFreeGrammar&, std::__cxx11::basic_string, std::allocator >)'|

Karmen
  • 1
  • 3
  • Maybe because "xxx" is a not a string but a char array ? – vcloarec Jun 15 '18 at 00:52
  • @vcloarec Isn't that what Remy said? – Barmar Jun 15 '18 at 00:54
  • @Barmar : we have edited in the same time ... but does the Remy solution works ? because if the parameter is a reference, the compiler will not create a object. – vcloarec Jun 15 '18 at 00:55
  • @RemyLebeau: Shouldn't the compiler be able to convert from `const char*` to `string` just as easily as to `const string&`? It's the same implicit conversion; sure, avoiding the copy is nice when you are receiving an actual `string`, but it's not a compatibility issue. – ShadowRanger Jun 15 '18 at 00:57
  • 7
    It sounds like the *.cpp file containing the definition didn't get linked into the program. – aschepler Jun 15 '18 at 00:57
  • 1
    @vcloarec: `const` references are special; C++ allows them to hold temporaries created at time of assignment, and preserves them until the `const` reference goes out of scope (the exact rules are more complicated than that, but close enough). – ShadowRanger Jun 15 '18 at 00:59
  • @aschepler: Exactly. The code looks fine at first glance, so I'm thinking the linker lacks the definition. – ShadowRanger Jun 15 '18 at 00:59
  • @aschepler is avoiding us a conversation around const reference ! I am interrested with documentation about const reference. – vcloarec Jun 15 '18 at 01:00
  • 1
    @vcloarec the error message debunks that theory – M.M Jun 15 '18 at 01:07
  • Did you remember to actually compile this new cpp file? – user253751 Jun 15 '18 at 01:09
  • @M.M is ShadowRanger theory is false ? – vcloarec Jun 15 '18 at 01:11
  • 1
    @vcloarec what? I am referring to your theory. You can see from the error message that the function taking `string` was called – M.M Jun 15 '18 at 01:15
  • ok, i am confuse – vcloarec Jun 15 '18 at 01:16

0 Answers0