2011-04-11 59 views
1

如何将一个函数的正常返回值分配给指针?C++:将正常返回值分配给一个指针

例如,我要分配给此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构造函数?

在此先感谢。

+0

你想解决什么是真正的问题?我不确定你是否真的想要使用这种设计......(即在类中保留一个指针并使用返回整数的函数初始化它) – 2011-04-11 10:56:06

+0

@ David Rodriguez:我想使用函数返回的临时值将它复制并赋值给一个普通的变量,这对你有意义吗?在上面的这个小代码段中,好处并不明显,但我并不打算编写处理小块数据的小程序。 – 2011-04-11 12:11:56

回答

2

这样做:

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不是一个指针。

+1

不要忘了复制ctor和任务(规则三) – MSalters 2011-04-11 11:26:11

+0

@ MSalters:谢谢你的提醒。我添加到我的答案。 – Nawaz 2011-04-11 11:28:17

+1

感谢一堆。顺便说一句,鉴于我上面的情况,我的目标是使用临时数据(返回AnotherClass :: getInt()),而不是将其复制到一个正常的变量,你认为我在正确的轨道上? – 2011-04-11 12:18:55

-1

不,你不要到 - 只要确保你取消引用指针!

*m_ipA = AnotherClass::getInt(); 你真的应该不过,如果你打算不断修改m_ipA

2

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

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

非常感谢兄弟,你的答案是排名最高的。 – 2011-04-11 12:20:19

0
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。忘记释放内存。