【问题标题】:Initialising a class member dependant on another class member初始化依赖于另一个类成员的类成员
【发布时间】:2012-10-01 15:25:02
【问题描述】:
        class TestGet : public ::testing::Test 
        {
        protected:
            TestGet() 
                : _txHandle(11)
            {
                _interface.get = mockGet;
            }

            Interface_T _interface;
            Handle_T _txHandle;
            DB _db;
        };

如果我更改 DB 使其只有以下构造函数:

        explicit DB(Interface_T& _interface):
            _interface(interface)
        {
        }

我现在是否需要在我的TestGet 类中使用std::shared_ptr 声明_db,并在构造函数中使用_interface 对其进行初始化?

更新:

问题是我有:

    private:
        Interface_T _interface;

在 DB 类中而不是在引用中。

【问题讨论】:

  • 你的问题有点含糊。究竟是什么问题?在 _txHandle(11) 之后添加 , DB(_interface) 会起作用吗?

标签: c++ class constructor initialization


【解决方案1】:

这应该可行:

TestGet()
: _interface()
, _txHandle(11)
, _db(_interface)
{
    _interface.get = mockGet;
}

不过,这取决于DB 的构造函数是否做了不重要的事情。只要它只存储参考,这应该没问题。也就是说,DB 应该是这样的:

struct DB
{
    Interface_T & _interface;
    explicit DB(Interface_T & interface) : _interface(interface) { }
};

如果您需要进一步初始化,您可以在DB 中添加一个init() 函数,或者为Interface_T 创建一个初始化函数,您可以在TestGet 的构造函数中使用。

【讨论】:

  • 如果 DB 获得 _interface 的所有权怎么办?换句话说,如果它通过值而不是通过引用来存储接口?
  • @Baz:那么这将是一个完全不同的问题 :-)(另外,这不是“获得所有权”的意思。)
【解决方案2】:

我现在是否需要在我的 TestGet 类中使用 std::shared_ptr 声明 _db

不,您可以保持原样,但您必须在所有 TestGet 构造函数的初始化列表中对其进行初始化。

 TestGet() :
 _txHandle(11),
 _db(someInterface)
 {
     _interface.get = mockGet;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2011-02-17
    • 2023-03-27
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多