[英]Pointer to a Vector of Class - I can't reach the members of the Class
我尝试用指针创建一个向量(以便所有内容都存储在堆中/堆中)。 然后,我想用一个类的数组填充向量。 我正在考虑按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;
}
正如其他人建议的那样,如果您只想要tClass的向量,则可以执行以下操作
vector<tClass> vectorName (5);
并像这样访问它
vectorName[3].y;
但是,如果您想要向量tClass指针,则可以初始化并像这样访问它
vector<tClass*> vectorName(5);
vectorName[3]->y;
编辑
这可能会对您有所帮助,这是您的代码,并带有注释,以帮助您了解发生了什么问题
class tClass
{private:int x = 0; 公开:int y = 0; tClass(){cout <<“ New” << 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;
}
请注意,尽管这样会产生错误,因为类指针的向量未指向任何类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.