I'm new to C++. I search many times, but still can't get the answer. I'm writing a class named Course to describe the courses students taking at school. The Course class has 3 fileds:
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: no match for call to ‘(std::string {aka std::basic_string}) (std::string&)’ I also tried to modify the code to Course &setName(string &name)... And the compiler keeps complaining about the same error.
But if I change the code to:
Course &setName(string name)
{
this->courseName = name;
return (*this);
}
Then it works well. I couldn't understand what the compiler is complaining about and why I can't use the direct initialization?
std::string::c_strReturns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
std::basic_string is a class template for making strings out of character types, std::string is a typedef for a specialization of that class template for char .
There is no functionality difference between string and std::string because they're the same type.
string is in the std namespace. You have the following options: Write using namespace std; after the include and enable all the std names: then you can write only string on your program. Write using std::string after the include to enable std::string : then you can write only string on your program.
I couldn't understand what the compiler is complaining about and why I can't use the direct initialization?
Because that's not an initialization. That's an assignment. Both assignment an (copy-)initialization make use of the =
sign, but don't let that fool you: the two things are fundamentally different.
Initialization is what gives a value to an object upon construction. When your setName()
member function gets called, the object on which it is invoked (as well as its data members) have already been constructed. If you want to initialize them there, you're late: you've missed the train.
In a constructor's initialization list, on the other hand, you could initialize your data members as follows:
Course::Course(std::string name) : courseName(std::move(name)) { }
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
// This would be initialization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With