指向类矢量的指针 - 我无法联系到班级成员

时间:2016-01-26 14:18:07

标签: c++ class pointers vector heap

我尝试使用指针创建一个向量(以便所有内容都存储在堆中/堆上)。然后我想用一个类的数组填充向量。我正在考虑通过class[i].member访问课程......可悲的是,它不起作用。 如果我在没有矢量的情况下尝试这个,它就会起作用,如:

tClass *MyClass = new tClass[5]

我在没有特定目的的情况下尝试这个,只是为了更好地理解C ++。任何人都可以看看我错了吗?谢谢!

以下是代码:

#include "iostream"
#include "vector"
using namespace std;

class tClass
{
private:
   int x = 0;
public:
   int y = 0;
tClass(){cout << "New" << endl;};
~tClass(){}; //do I need to make a delete here?

int main ()
{
   vector<tClass> *MyClass[5];
   MyClass = new vector<tClass>[5];
   cout << MyClass[3].y << endl;
   delete[] MyClass;
}

1 个答案:

答案 0 :(得分:0)

正如其他人所建议的那样,如果你只想要一个tClass的向量,你可以做以下

vector<tClass> vectorName (5);

并像这样访问

vectorName[3].y;

但是如果你想要一个tClass指针的向量,你可以初始化并像这样使用

vector<tClass*> vectorName(5);
vectorName[3]->y;

修改

这可能对您有所帮助,这是您的代码,并附有评论以帮助您了解出现了什么问题

class tClass

{ 私人的:     int x = 0; 上市:     int y = 0;     tClass(){cout&lt;&lt; “新”&lt;&lt; ENDL; };     〜tClass(){}; //我需要在这里删除吗? //不,你不需要在这里删除,因为这个类不包含“新闻”

int main()
{
    vector<tClass> *MyClass[5]; //use () to give a vector an initial size, [] is only to access a member
                                //also to have a vector holding pointers, the asterisk needs to be after tClass not before the vector name
    MyClass = new vector<tClass>[5];        
    cout << MyClass[3].y << endl;       //discused above
    delete[] MyClass;                   //only needed if a new is used, however you dont need one here, as it will just go out of scope
}

这里是你的代码,但修复了使用指针编译和运行

#include <iostream>
#include <vector>
using namespace std;

class tClass
{
private:
    int x = 0;
public:
    int y = 0;
    tClass(){ cout << "New" << endl; };
};

int main()
{
    vector<tClass*> MyClass(5);
    cout << MyClass[3]->y << endl;
}

请注意,这会产生错误,因为类指针的向量不指向任何类