加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c数组声明在一个标题

发布时间:2020-12-16 07:51:20 所属栏目:百科 来源:网络整理
导读:我想知道是否可以声明一个数组(此时大小不知道),作为一个类的私有成员,然后在该类的构造函数中设置大小.例如: class Test {int a[];public:Test(int size);};Test::Test(int size) {a[size]; // this is wrong,but what can i do here?} 这是可能的还是应该
我想知道是否可以声明一个数组(此时大小不知道),作为一个类的私有成员,然后在该类的构造函数中设置大小.例如:
class Test {
int a[];
public:
Test(int size);
};

Test::Test(int size) {
a[size];   // this is wrong,but what can i do here?
}

这是可能的还是应该使用动态数组?谢谢!

解决方法

不,这是不可能的.标头中的数组声明必须具有恒定大小的值.否则,像“sizeof”这样的构造就不可能正常运行.您需要将数组声明为指针类型,并在构造函数中使用new [].例.
class Test { 
    int *a;
public:
    Test(int size) {
       a = new int[size];
    }
    ~Test() { delete [] a; }
private:
    Test(const Test& other);
    Test& operator=(const Test& other);
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读