【问题标题】:initializing private class variable of std::string&初始化 std::string& 的私有类变量
【发布时间】: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&amp;?为什么不只是一个string?使类数据成员成为引用是一件复杂的事情,因为您不能从一开始就将其未初始化为某些 actual 字符串。

标签: c++ c++11


【解决方案1】:

让我们先修复默认构造函数:你不能用赋值来初始化引用。它们需要使用初始化列表进行初始化:

static string empty_name("");

A::A(void) : name (empty_name) {  
}

注意empty_name 变量的使用,作用域为翻译单元。这使您可以初始化某个对象的引用成员。

load 成员函数而言,没有办法在创建后重新分配引用。如果您需要此功能,最好的办法是在需要访问外部 std::string 对象时用指针替换引用,如果不需要引用字符串,则用副本(即 std::string name)在您的对象之外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2013-07-18
    • 2014-08-15
    相关资源
    最近更新 更多