在构造函数中初始化指针的正确方法 [英] Right way to initialize a pointer in a constructor

查看:759
本文介绍了在构造函数中初始化指针的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下练习:



添加代码,使其正常运行。

  class MyInt 
{
public:

private:
int * MyValue
}

int main(int argc,char ** argv)
{
MyInt x(1);
... //更多的代码,其中x的实际值将被使用。
return 0;
}

我作为私有属性添加

  int val; 

和一个公共构造函数

  Myint(int x)
{
val = x;
MyValue =& val;
}

我添加了int val作为一种方式为构造函数分配给MyVal



是否有一个简洁的方法来回答这个练习?

另一种方式:

  MyInt(int x):MyValue (new int(x)){} 

这不需要额外的成员。但是,您必须确保在析构函数中释放内存。

 〜MyInt(){delete MyValue; } 


I have the following exercise:

Add code to make it run properly.

class MyInt
{
public:

private:
    int* MyValue;
}

int main(int argc,char** argv)
{
 MyInt x(1);
 ...//a bit more code where the actual value of x is going to be used.
 return 0;
}

I added as a private property

int val;

and a public constructor

Myint(int x)
{
    val = x;
    MyValue = &val;
}

I added the int val as a way for the constructor to assign to MyVal an address of an object that is not temporary, as the x.

Is there a neat(er) way to answer this exercise?

解决方案

Another way:

MyInt(int x) : MyValue(new int(x)) {}

This doesn't require the additional member. However, you have to make sure that you deallocate the memory in the destructor.

~MyInt() { delete MyValue; }

这篇关于在构造函数中初始化指针的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆