所以今天早些时候,我正在 catch 很好的旧 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;
}
我遇到了这些错误:
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
但是,在构造函数中添加 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;
}
现在,有几个问题:
- 如果没有用于传递的
const
,为什么代码无法工作 引用?在你的文件中总是通过引用传递是一种好习惯吗 构造函数,如果是,是否意味着我们必须使用const
关键词? - 因此,如果我在构造函数中按值传递,那么说:
Names(string name, string surname) : _name(name), _surname(surname) {}
这是否意味着_name
和_surname
为空或者他们是 通过的值。我知道在按值传递时,变量的拷贝 正在对拷贝进行更改。但是什么时候 拷贝被破坏或超出范围?这有点令人困惑。
谢谢
最佳答案
A string literal必须转换为 std::string
,这将是一个临时的,而你 cannot pass a temporary by non-const reference .
关于C++ 构造函数——通过引用传递仅适用于 const。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33609777/