C ++ Error: no match for calling '(std :: string {aka std :: basic_string <char>}) (std :: string &)
I am new to C ++. I searched many times, but still I canβt get an answer. I am writing a class called "Course" to describe the courses students take at school. The class of the course has 3 fields:
protected: string courseName; int courseNum; float score; And I have a public method "setName" to set the course name:
Course &setName(string name) { this->courseName(name); return (*this); } However, when I tried to compile, the compiler complains that: C ++ error: there is no match for the call '(std :: string {aka std :: basic_string}) (std :: string &) I also tried changing the code to Course & setName (string & name) ... And the compiler continues to complain about the same error.
But if I changed the code to:
Course &setName(string name) { this->courseName = name; return (*this); } Then it works well. I could not understand what the compiler was complaining about and why I could not use direct initialization?
I could not understand what the compiler was complaining about, and why I could not use direct initialization?
Because this is not initialization. This task. Both (copy-) initialization assignments use the = sign, but don't let this fool you: the two things are fundamentally different.
Initialization is what gives meaning to an object in construction . When your setName() member setName() is called, the object on which it is called (as well as its data elements) is already constructed. If you want to initialize them, you are late: you missed the train.
In the constructor initialization list, on the other hand, you can initialize your data as follows:
Course::Course(std::string name) : courseName(std::move(name)) { } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ // This would be initialization You are trying to assign the value of one row to another that has already been initialized. The syntax for this is
std::string s1 = ....; std::string s2 = ....; s2 = s1; // OK, assignment while you are trying to fulfill the equivalent
s2(s1); // error, this is no way to assign s1 to s2 and it is not syntactically valid in this context. You cannot initialize objects that have already been built.