将对象分配给C ++类构造函数中的成员变量

问题描述

我要

error: use of deleted function ‘PropertyLink& PropertyLink::operator=(PropertyLink&&)’

当我尝试将一个对象分配给所构造的类中的成员变量时。

我有2个类定义PropertyLinkNodeBlock。并且我想在构造PropertyLink对象时在NodeBlock内创建NodeBlock对象。

以下是类定义

PropertyLink.h

class PropertyLink {
    
   public:
    PropertyLink(unsigned int);
    PropertyLink();
};

PropertyLink.cpp

#include "PropertyLink.h"

PropertyLink::PropertyLink(unsigned int propertyBlockAddress): blockAddress(propertyBlockAddress) {};
PropertyLink::PropertyLink(): blockAddress(0) {};

NodeBlock.h

#include "PropertyLink.h"
class NodeBlock {
   public:
    PropertyLink properties;

    NodeBlock(unsigned int propRef) {
        properties = PropertyLink(propRef);
        // properties(propRef); // error: no match for call to ‘(PropertyLink) (unsigned int&)’
        // properties = new PropertyLink(propRef); // tried this too none of them worked
    };
};

在编译器输出中,有一条注释说

note: ‘PropertyLink& PropertyLink::operator=(const PropertyLink&)’ is implicitly deleted because the default deFinition would be ill-formed:
[build]     9 | class PropertyLink {

解决方法

似乎PropertyLink的复制/移动分配运算符不可用。您可以(并且应该)直接初始化properties,而不是在构造函数的主体中进行分配。

您可以使用成员初始化器列表。

class NodeBlock {
   public:
    PropertyLink properties;
    NodeBlock(unsigned int propRef) : properties(propRef) {}
};