使用引用的C ++错误

时间:2017-08-04 10:58:40

标签: c++

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

Book.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();
};

Book.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;
}

1 个答案:

答案 0 :(得分:1)

A reference is essentially an alias for an existing object. It must be initialized upon definition. You can't say "<a name>" is an alias for whatever you don't know.

A reference must be initialized and cannot be changed after initialization.

In your case, if you want to have a default constructor that does not assign anything, you'd better create an object representing "unassigned" and use that.

private:
    static const Author nullAuthor(a_flag_that_means_unassigned);
public:
    Book::Book() : bookAuthor(nullAuthor);

If you want to assign ot change it later, use a regular object. Make sure you have a copy assigner for class Author.

private:
    Author bookAuthor;
public:
    Book::Book(); // Now it's safe to leave it uninitialized