开发者

Static initialization of a struct with class members

开发者 https://www.devze.com 2022-12-30 13:54 出处:网络
I have a struct that\'s defined with a large number of vanilla char* pointers, but also an object member. When I try to statically initialize such a struct, I get a compiler error.

I have a struct that's defined with a large number of vanilla char* pointers, but also an object member. When I try to statically initialize such a struct, I get a compiler error.

typedef开发者_StackOverflow struct 
{
    const char* pszA;
    // ... snip ...
    const char* pszZ;

    SomeObject obj;
} example_struct;

// I only want to assign the first few members, the rest should be default
example_struct ex = { "a", "b" };

SomeObject has a public default constructor with no arguments, so I didn't think this would be a problem. But when I try to compile this (using VS), I get the following error:

error C2248: 'SomeObject::SomeObject' : cannot access private member declared in class 'SomeObject'

Any idea why?

Update: Here's the definition of SomeObject

class SomeObject
{
    void operator=(const SomeObject&);
    SomeObject(const SomeObject&);
public:
    SomeObject()
        {
            // etc
        }

    // members snipped
}


Your initialization of ex performs copy-initialization. It takes the value on the right and uses it to initialize the variable on the left. For class-type members, the appropriate constructor is used. In your case, that means invoking the copy constructor for SomeObject, but you've made that constructor private, so the compiler is correct in telling you that SomeObject::SomeObject is a private member that can't be accessed.

Although the compiler is allowed to elide the call to the copy constructor and initialize ex.obj directly with the default constructor, that is an optional optimization; it still needs to be allowed to call the copy constructor.

You can either give example_struct a constructor of your own and use that in place of brace initialization, or you can publicize SomeObject's copy constructor.


The rest of the members will be initialized to '0', not "default", right? So it's probably trying to call SomeObject(0), which I'd guess is resolving to a private copy constructor.


It looks like the constructor for SomeObject is private.

0

精彩评论

暂无评论...
验证码 换一张
取 消