C++ 构造函数——通过引用传递仅适用于 const。为什么?

标签 c++ c++11 parameter-passing pass-by-reference pass-by-value

所以今天早些时候,我正在 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;
}

现在,有几个问题:

  1. 如果没有用于传递的 const,为什么代码无法工作 引用?在你的文件中总是通过引用传递是一种好习惯吗 构造函数,如果是,是否意味着我们必须使用 const 关键词?
  2. 因此,如果我在构造函数中按值传递,那么说: 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/

相关文章:

c++ - 对可变参数模板类型列表的每种类型进行操作的函数

c++ - 将 Eigen 类型与 STL 容器和 std::vector 一起使用

c++ - 将 "normal"参数转换为模板化参数是否正确?

c++ - 了解clock_gettime()的不同时钟

c++ - 在 C++ 中使用 rpcgen

c++ - 我如何将静态 vector 添加到类中

C++ 从非右值对象访问右值引用对象

c - 如何正确传递这个 C 字符串数组?

jquery - 如何通过 .change 触发器传递 html 元素引用

c++ - 表达式模板中的按引用捕获可以与类型推导共存吗?