l_xox_l 2022-09-15 19:37 采纳率: 81.3%
浏览 16
已结题

c++this指针问题

问题
在含参构造函数中
this->m_arry = new T[this->m_capacity];
请问一下[]中的this->m_capacity前面加了后为什么说我非法间接寻址
this->m_arry是m_arry的地址
[]中不是要填一个值吗,然后我就在this->m_capacity前面加了个
进行解引用但是系统报错删了就不报错了

#include <iostream>
using namespace std;

template<class T>
class fruit
{
public:
    fruit(int capacity){
        cout << "构造函数" << endl;
        this->m_capacity = capacity;
        this->m_size = 0;
        this->m_arry = new T[this->m_capacity];
    }

    fruit(const fruit&p){
        this->m_capacity = p.m_capacity;
        this->m_size = p.m_size;
        this->m_arry = new T[p.m_capacity];
        for (int i=0; i < this->m_size; i++)
        {
            this->m_arry[i] = p.m_arry[i];
        }
    }
    fruit& operator=(const fruit&p){
        cout << "operato=函数重载" << endl;
        if (this->m_arry != NULL)
        {
            delete[]this->m_arry;
            this->m_arry = NULL;
            this->m_capacity = 0;
            this->m_size = 0;
        }

        this->m_size = p.m_size;
        this->m_capacity = p.m_capacity;
        this->m_arry = new T[p.m_capacity];
        for (int i=0; i < this->m_size; i++)
        {
            this->m_arry[i] = p.m_arry[i];
        }
        return *this;
    }

    ~fruit()
    {
        if (this->m_arry != NULL)
        {
            delete[]this->m_arry;
            this->m_arry = NULL;
        }
    }

    
private:
    //数组容量
    int m_capacity;
    //数组元素个数
    int m_size;

    T* m_arry;
}

  • 写回答

2条回答 默认 最新

  • 快乐鹦鹉 2022-09-15 19:49
    关注

    this->m_arry = new T[this->m_capacity];
    m_capacity本来就是int类型,直接用就可以了啊,你为啥要加*号呢?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月27日
  • 已采纳回答 10月19日
  • 创建了问题 9月15日

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计