简体   繁体   English

在 C++ 中将成员初始化为 NULL

[英]initialize member to NULL in C++

I need to instantiate a class A without initializing its member B which must be initialized later passing special parameters to its constructor.我需要实例化一个类 A 而不初始化它的成员 B,它必须在稍后将特殊参数传递给它的构造函数来初始化。 I am trying to pass a NULL but an error is returned, here is the SSCCE:我试图传递一个 NULL 但返回一个错误,这里是 SSCCE:

#include<stdio.h>

class B
{
    private:
        int b;
        int c;
    public:
        B(int b, int c){this->b = b; this->c = c;};
};

class A
{
    private:
        B b;
    public:
        A(): b(NULL)
        {};
};

int main()      //main function declaration
{
    A a = A();
    return 0;       //terminating function
}

the returned error is:返回的错误是:

g++ test.c 
test.c: In constructor ‘A::A()’:
test.c:17:14: error: no matching function for call to ‘B::B(NULL)’
   17 |   A(): b(NULL)
      |              ^
test.c:9:3: note: candidate: ‘B::B(int, int)’
    9 |   B(int b, int c){this->b = b; this->c = c;};
      |   ^
test.c:9:3: note:   candidate expects 2 arguments, 1 provided
test.c:3:7: note: candidate: ‘constexpr B::B(const B&)’
    3 | class B
      |       ^
test.c:3:7: note:   no known conversion for argument 1 from ‘long int’ to ‘const B&’
test.c:3:7: note: candidate: ‘constexpr B::B(B&&)’
test.c:3:7: note:   no known conversion for argument 1 from ‘long int’ to ‘B&&’

You class A aggregates a B .A类聚合了B Each instance of A has a B , always. A每个实例总是有一个B It's not meaning to set an A 's B to null .ABnull并不意味着。

Want you may want is for the B member of an A to be default initialized.您可能希望AB成员被默认初始化。 You can do that by providing a default constructor for B :您可以通过为B提供默认构造函数来做到这一点:

class B
{
private:
    int b;
    int c;
public:
    B():b(0), c(0) {};
    B(int b, int c){this->b = b; this->c = c;};
};

Or even just provide default initializer in the class itself:或者甚至只是在类本身中提供默认初始值设定项:

class B
{
private:
    int b=0;
    int c=0;
public:
    B() {};
    B(int b, int c){this->b = b; this->c = c;};
};

in both case, you then have, simply:在这两种情况下,您只需:

    A(){};

If you can compile with c++17 I will recommend using std::optional , otherwise you can consider having a default constructor for B , B() = default;如果您可以使用 c++17 进行编译,我将推荐使用std::optional ,否则您可以考虑为B使用默认构造函数, B() = default; or dynamic allocation together with checking for nullptr或动态分配以及检查nullptr

you are only passing a single attribute right?你只传递一个属性对吗? try with 2 nulls尝试使用 2 个空值

its just my suggestion,这只是我的建议,

usually that error comes ,when you intialise with wrong attributes通常,当您使用错误的属性初始化时,会出现该错误

  A(): b(NULL,NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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