How do I assign a normal return value of a function to a pointer?
For example, I want to assign the return value of this static
member function:
int AnotherClass::getInt();
In the following expression :
// 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
}
Do I need to initialize m_ipA
with the new
keyword in t开发者_如何学运维he constructor?
Thanks in advance.
If m_ipA
is not pointing to any valid memory location then you need to allocate memory like following:
m_ipA = new int(AnotherClass::getInt());
Do this:
m_ipA = new int; //do this also, if you've not allocated memory already.
*m_ipA = AnotherClass::getInt();
You may want to allocate memory in the constructor of the class as:
Class::Class() //constructor
{
m_ipA = new int; //allocation
}
void Class::printOutput()
{
*m_ipA = AnotherClass::getInt();
}
Class::~Class() //destructor
{
delete m_ipA; //deallocation
}
EDIT:
As MSalters reminded: when you've pointers in your class, then don't forget the copy ctor and assignment (Rule of Three).
Or mabye, you don't want pointer to int. I mean, the following might work for you:
int m_int;
m_int = AnotherClass::getInt();
Notice m_int
is not a pointer.
m_ipA = new int;
*m_ipA = AnotherClass::getInt();
//Use m_ipA
delete m_ipA; //Deallocate memory, usually in the destructor of Class.
Or use some RAI such as an auto_ptr. To forget about deallocating memory.
No, you don't have to - just make sure you dereference the pointer!
*m_ipA = AnotherClass::getInt();
You really should though, if you intend to continually modify m_ipA
精彩评论