简体   繁体   中英

Assign object to a member variable in C++ class constructor

I'm getting

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

When I try to assign an object to a member variable in the class constructed.

I have 2 class definitions, PropertyLink and NodeBlock . and I want to create an object of PropertyLink inside NodeBlock when constructing a NodeBlock object.

Following are the class definitions

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

In the compiler output, there is a note saying

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

It seems the copy/move assignment operator of PropertyLink is not usable. You can (and should) initialize properties directly instead of assigning it in constructor's body.

You can use member initializer list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM