使用引用的 C++ 错误

标签 c++

我在做一个项目,这是我第一次使用指针和引用,此时我需要设置对写书的Author的引用,作为构造函数中的参数。我还想返回对作者的常量引用,使用 getAuthor() 方法。我不明白为什么会出现该错误(注释行)。

书.h

class Book{
private:
    std::string bookTitle;
    const Author &bookAuthor;
    std::string bookLanguage;

public:
    Book(std::string _title, const Author &_author, std::string _language);
    Book();
    ~Book();
    Author getAuthor();
};

图书.cpp

#include "Book.h"

Book::Book(std::string _title, const Author &_author, std::string _language) 
: bookTitle(_title), bookAuthor(_author), bookLanguage(_language){
}

Book::Book(){ // error C2758: 'Book::bookAuthor' : a member of reference 
              // type must be initialized
}

Book::~Book(){
};

Author Book::getAuthor(){
    return bookAuthor;
}

最佳答案

关于使用引用的 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45505072/

相关文章:

MFC 对话框错误中的 C++ 多线程

c++ - 无法在 VS 2015 中编译 CUDA 代码

c++ - 编译错误 Undefined symbols for architecture x86_64 :

c++ - std::uninitialized_fill() 和 std::get_temporary_buffer()

c++ - 如何在 C++ 中使用更高的精度

c++ - 什么场景可能需要使用\需要指向(非常量\常量)数据的常量指针

c++ - 如何在 C++ 中为 USB 投影仪使用 DLL 接口(interface)

c++ - 如何在 dev c++ 上运行客户端服务器程序?

c++ - 我可以在没有默认初始化的情况下初始化数组的 std::unique_ptr (我只想让它具有虚拟值)

c++ - 实现定义的行为和读取 unicode 到缓冲区