参数传入空指针并在函数内部赋值

1.   当把一个指针作为参数时,指针不能为未指向地址的值,必须为一个指向确定地址的值

void main()
{
  Base *base;
  //base=new Base();//需要加上此句
  handle(a);//错误
}
void handle(Base *t)
{
  cout<<base->number<<endl;
}


2.如果非要使用空指针,在函数内部赋值的话可以按照下面的方式写,1.参数为取地址符或者指针的指针2.函数内为空指针分配空间,退出testPtr后,函数中的赋值仍然存在

void testPtr(Base **base)
{
   *base = new Base;
   std::cout<<( *base)->number;
}
void main()
{
  Base *base=nullptr;
  testPtr(base);
}

猜你喜欢

转载自blog.csdn.net/wang371372/article/details/51304003