So, earlier today I was catching up with the good old C ++, and when I compiled my code, it did not work. Like some programmers, I started to crack, and eventually found that adding a keyboard constfixes the problem. However, I donβt like to hack a lot and want to find out why the code worked fine after adding const.
This was my code BEFORE adding constto the constructor:
#include <iostream>
#include <string>
using namespace std;
class Names {
private:
string _name;
string _surname;
public:
Names(string &name, string &surname) : _name(name), _surname(surname) {}
string getName() const {return _name;}
string getSurname() const {return _surname;}
};
int main(){
Names names("Mike", "Man");
cout << names.getName() << endl;
cout << names.getSurname() << endl;
}
I was getting these errors:
names.cc:19:27: error: no matching function for call to βNames::Names(const char [5], const char [4])β
Names names("Mike", "Man");
^
names.cc:19:27: note: candidates are:
names.cc:11:2: note: Names::Names(std::string&, std::string&)
Names(string &name, string &surname) : _name(name), _surname(surname) {}
^
names.cc:11:2: note: no known conversion for argument 1 from βconst char [5]β to βstd::string& {aka std::basic_string<char>&}β
names.cc:5:7: note: Names::Names(const Names&)
class Names {
^
names.cc:5:7: note: candidate expects 1 argument, 2 provided
<builtin>: recipe for target 'names' failed
make: *** [names] Error 1
However, after adding a keyword constinside the constructor Names(string const &name, string const &surname) : _name(name), _surname(surname) {}, it works.
This is my working code:
#include <iostream>
#include <string>
using namespace std;
class Names {
private:
string _name;
string _surname;
public:
Names(string const &name, string const &surname) : _name(name), _surname(surname) {}
string getName() const {return _name;}
string getSurname() const {return _surname;}
};
int main(){
Names names("Mike", "Man");
cout << names.getName() << endl;
cout << names.getSurname() << endl;
}
Now a few questions:
const
?
, , const
?- , , :
Names(string name, string surname) : _name(name), _surname(surname) {} , _name _surname
. pass by value,
.
? .
user5359494