C++ C++;:将正常返回值指定给指针

C++ C++;:将正常返回值指定给指针,c++,pointers,return,C++,Pointers,Return,如何将函数的正常返回值指定给指针 例如,我想分配此静态成员函数的返回值: 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

如何将函数的正常返回值指定给指针

例如,我想分配此
静态
成员函数的返回值:

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 = 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
}
编辑:

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

或者mabye,您不希望指针指向int。我的意思是,以下内容可能适合您:

int m_int; 

m_int = AnotherClass::getInt(); 
请注意
m_int
不是指针。

不,您不必-只要确保取消引用指针即可

*m_ipA=AnotherClass::getInt()

但是,您确实应该这样做,如果您打算继续修改m_ipA

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

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

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

您想要解决的真正问题是什么?我不确定你是否真的想用那种设计。。。(例如,在类中保留一个指针,并让它由返回整数的函数初始化@David Rodriguez:我想使用该函数返回的临时值,而不是复制它并将其分配给普通变量。这对您有意义吗?在上面这样一个小片段中,好处并不明显,但我不打算编写小的程序总是处理一小块数据。别忘了复制ctor和赋值(三个规则)@MSalters:谢谢你的提醒。我把它添加到了我的答案中。非常感谢。顺便说一句,考虑到我的上述情况和我使用临时数据的目标(由另一个类::getInt()返回)与其把它复制到一个普通变量,你认为我的方法正确吗?@Tom:
getInt()
返回
int
。所以你不必担心它,因为你在调用站点得到的不是“临时的”只要变量
m_-ipA
保存分配给它的内存,你就拥有它。所以底线是:别担心。@Tom:或者mabye,你不想指针指向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.