4 c++ parameter-passing pass-by-reference pass-by-value c++11
所以今天早些时候,我正在追赶好的旧C++,当我编译代码时,它无法正常工作.像一些程序员一样,我开始讨厌,并最终发现添加键盘const解决了这个问题.但是,我不喜欢黑客攻击很多,并且想要找出为什么代码在添加之后工作正常const.
这是我的代码之前添加const到构造函数:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我收到这些错误:
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
Run Code Online (Sandbox Code Playgroud)
但是,在const构造函数中添加关键字后Names(string const &name, string const &surname) : _name(name), _surname(surname) {}- 它似乎正在工作.
这是我的工作代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
现在,几个问题:
const不能通过引用传递?在构造函数中始终通过引用传递是一种好习惯,如果是这样,那么我们必须使用const
关键字?Names(string name, string surname) : _name(name), _surname(surname) {}这是否意味着_name和_surname是零或者是他们传递的值.我知道在传递值时,正在制作变量的副本并且正在对副本进行更改.但是什么时候副本会被破坏或超出范围?这有点令人困惑.谢谢
Cor*_*mer 14
必须将字符串文字转换为a std::string,这将是一个临时的,并且您不能通过非const引用传递临时字符.
| 归档时间: |
|
| 查看次数: |
614 次 |
| 最近记录: |