C++:将正常返回值分配给指针

C++ : Assign normal return value to a pointer

本文关键字:分配 指针 返回值 C++      更新时间:2023-10-16

如何将函数的正常返回值分配给指针?

例如,我想分配这个static成员函数的返回值:

int AnotherClass::getInt();

在以下表达式中:

// m_ipA is a private member of the class `Class`
int *m_ipA;
// Lots of things in between, then :
void Class::printOutput() {
    m_ipA = AnotherClass::getInt();
    // Some operations on m_iPA here, then
    // Print instructions here
}

是否需要在构造函数中使用new关键字初始化m_ipA

提前谢谢。

如果m_ipA没有指向任何有效的内存位置,那么您需要如下分配内存:

m_ipA = new int(AnotherClass::getInt());

这样做:

 m_ipA = new int; //do this also, if you've not allocated memory already.
*m_ipA = AnotherClass::getInt();

您可能希望在类的构造函数中分配内存为:

Class::Class() //constructor
{
  m_ipA = new int; //allocation
}
void Class::printOutput() 
{
    *m_ipA = AnotherClass::getInt();
}
Class::~Class() //destructor
{
  delete m_ipA; //deallocation
}

编辑:

正如MSchangers提醒的那样:当你的类中有指针时,不要忘记复制ctor和赋值(三条规则(。

也许,您不希望指针指向int。我的意思是,以下可能对你有用:

int m_int; 
m_int = AnotherClass::getInt(); 

请注意,m_int不是指针。

m_ipA = new int;
*m_ipA = AnotherClass::getInt();
//Use m_ipA
delete m_ipA; //Deallocate memory, usually in the destructor of Class.

或者使用一些RAI,例如auto_ptr。忘记释放内存。

不,您不需要-只需确保取消引用指针!

*m_ipA = AnotherClass::getInt();不过,如果您打算继续修改m_ipA

,您确实应该这样做