【发布时间】:2016-12-12 21:21:41
【问题描述】:
如何在我的 c++ 类中初始化我的私有变量?
啊哈:
class A {
private:
std::string& name;
public:
A(void);
~A(void);
bool load(std::string& name);
};
a.cpp:
#include <string>
#include "a.h"
A::A(void) {
this->name = "";
}
A::~A(void) {}
bool A::load(std::string& name) {
this->name = name;
}
错误:
a.cpp: In constructor ‘A::A()’:
a.cpp:3:1: error: uninitialized reference member in ‘std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}’ [-fpermissive]
A::A(void) {
^
In file included from a.cpp:2:0:
a.h:3:22: note: ‘std::__cxx11::string& A::name’ should be initialized
std::string& name;
我已经在我的构造函数中初始化了它(在 a.cpp 中),但它仍然出错。
【问题讨论】:
-
为什么需要
name成为string&?为什么不只是一个string?使类数据成员成为引用是一件复杂的事情,因为您不能从一开始就将其未初始化为某些 actual 字符串。