Hi everyone,
I just wrote this piece of code to test something, but it didn't go through the GCC-compiler because of the following error:
C:\Project\TESTS\QtCreator_Pro\Constructers\main.cpp:22: ERROR: invalid initialization of non-const reference of type 'std::__cxx11::string& {aka std::__cxx11::basic_string<char>&}' from an rvalue of type 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}'
Person pers{"Manu", 2500};
class Person{
public:
Person(std::string &n, double sal): name{n}, salary{sal}
{
}
private:
std::string name;
double salary;
};
int main()
{
Person pers{"Manu", 2500};
return 0;
}
Please consider the first parameter of the constructor. It is a non-const. the code would not work unless I turn this parameter to const reference: Person(const std::string &n, double sal) or
I declare it just as a value, not as a reference: Person(std::string n, double sal).
But why ist that so? although readed the error-massage it is still not obvious to me why I need a const reference to string in my constructor in order to make my object like shown in the main function: Person pers{"Manu", 2500};
https://19216801.win/ https://routerlogin.cloud/ https://192168101.red/
can anyone teach me about this issue or about constructors, references, or strings in this particular contex?
Thanks a lot.