【问题标题】:Declaring an array of pointers to objects dynamically in C++在 C++ 中动态声明指向对象的指针数组
【发布时间】:2014-09-09 02:51:02
【问题描述】:

我必须在 C++ 中声明一个指向(类)对象的指针数组。我认为这是唯一的方法,但显然我错了,因为当我尝试编译它时会引发语法错误。具体来说,在我收到的 7 个错误中,其中 2 个错误位于以下行中:我使用“new”创建数组的位置,以及调用“setData()”函数的行中。你能告诉我哪里出错了吗?谢谢。

#include <iostream>

class Test
{
    public:
        int x;

        Test() { x=0; }
        void setData(int n) { x=n; }
};

void main()
{
    int n;
    Test **a;

    cin >> n;
    a=new *Test[n];

    for(int i=0; i<n; i++)
    {
        *(a+i)=new Test();
        *(a+i)->setData(i*3);
    }
}

【问题讨论】:

    标签: c++ arrays class pointers object


    【解决方案1】:

    使用a=new Test*[n];
    除此之外,您的程序中没有删除,琐碎的 getter/setter
    因为公共变量很奇怪,*(a+i) 可能是a[i]

    【讨论】:

    • 非常感谢,它成功了。但是,你能告诉我在类名之前和之后放置星号有什么区别吗?为什么我不能使用 *(a+i) (虽然我知道 a[i] 更好),还是?
    • 关于a[i]:你也可以使用其他东西,但为什么呢?关于星号:语言就是这样写的;你不能重新排序一切。对于new int[10][10]new intnew [10]int 也会出错...
    • 好的...但是 *(a+i)->setData() 不起作用,它会引发错误。我必须使用 a[i]。
    • (*(a+i))-&gt;setData()
    【解决方案2】:

    您的语法很接近,但略有偏差。改用这个:

    Test **a;
    
    ...
    
    a=new Test*[n];
    
    for(int i=0; i<n; i++)
    {
        a[i]=new Test();
        a[i]->setData(i*3);
    }
    
    ...
    
    // don't forget to free the memory when finished...
    
    for(int i=0; i<n; i++)
    {
        delete a[i];
    }
    
    delete[] a;
    

    由于您使用的是 C++,因此您应该改用 std::vector。我还建议将所需的值传递给类构造函数:

    #include <iostream>
    #include <vector>
    
    class Test
    {
        public:
            int x;
    
            Test(int n = 0) : x(n) { }
            Test(const Test &t) : x(t.x) { }
            void setData(int n) { x=n; }
    };
    
    int main()
    {
        int n;
        std::vector<Test> a;
    
        cin >> n;
        a.reserve(n);
    
        for(int i=0; i<n; i++)
        {
            a.push_back(Test(i*3));
        }
    
        ...
    
        // memory is freed automatically when finished...
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      相关资源
      最近更新 更多