C++:将正常返回值分配给指针
C++ : Assign normal return value to a pointer
如何将函数的正常返回值分配给指针?
例如,我想分配这个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
相关文章:
- 通过双指针分配指针
- 在不工作的情况下为数组分配指针,但反过来也可以
- 无法使用"std::make_shared"分配指针
- 分配指针时出现分段错误
- 为什么有时仅使用Ampersand运算符在C 中分配指针
- 重新分配指针阵列的一部分的安全方法
- 为什么在执行增量操作之前分配指针值
- 当指针指向的对象被另一个类的实例删除时,重新分配指针
- 在堆上分配指针的原因是什么?
- 有没有办法防止分配指针?
- 将运算符重写应用于具有动态分配指针的类
- 在堆上分配指针数组
- 在另一个结构中的结构内解除分配指针
- 分配指针后,是否可以为指针指向的事物分配变量名称?
- 重新分配指针后,将类功能与指针一起使用
- 为什么我的新分配指针会自动在程序退出上删除
- 分配指针的方法之间有什么区别?
- 如何声明和分配指针
- 内存分配(指针和堆栈)
- 通过参数分配指针的值