Domanda

void Foo::Bar(Baz& x)
{
z = &x;
}

Foo* foo;

foo -> Bar(nullptr);

I'm trying to create a generic template, Baz, using just typedef. Since z is private and belongs to Foo, I have trouble assigning nullptr to z.

If possible, I'd like the best way to set z to a nullptr without changing too much of the implementation-- unless this is that bad of an implementation.

I was thinking maybe

(Baz *) 0, or *(void * )0 or the Nullable Class .

È stato utile?

Soluzione

If you do want to keep this method:

void Foo::Bar(Baz& x)
{
  z = &x;
}

But still want to be able to set z as nullptr, you can add an overload for Bar that specifically takes a nullptr argument:

void Foo::Bar(std::nullptr_t nullp)
{
  z = nullp;
}

Altri suggerimenti

If you want Foo::Bar to take nullptr, you need to change parameter to pointer type:

void Foo::Bar(Baz* x)
{
   z = x;
}

Foo* foo = new Foo(); 

foo -> Bar(nullptr);

Note: you need to allocate object for foo pointer before using it, otherwise behavior is undefined.

nullptr is a pointer, not a valid reference:

int &v = nullptr;

The gcc complains:

bla.cpp:1:10: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘std::nullptr_t’
 int &v = nullptr;

So you can't pass it as a reference argument. If you want to be able to pass it change x to be a (possibly const) pointer:

void Foo::Bar(Baz* const x) {
   z = x;
}
void Foo::Bar(Baz* x)
{
z = x;
}

Foo* foo;
Baz* ptr = NULL;
foo -> Bar(ptr);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top