【发布时间】:2021-07-09 14:59:27
【问题描述】:
#include <iostream>
#include <vector>
using namespace std;
class Test
{
private:
int ID;
string name;
public:
Test(int ID, string name);
};
Test::Test(int ID, string name)
{
this->ID = ID;
this->name = name;
}
int main()
{
vector<Test *> test_vect;
Test *ptr = new Test(100, "John");
test_vect.push_back(ptr);
cout << ptr->ID << endl;
return 0;
}
这是我正在尝试的简单代码。
我想访问我存储在向量中的数据。
我认为可以通过使用 -> 来访问它,就像 struct 的向量一样,但我不能。所以我想知道如何在类中加载数据。
此外,我认为使用new 将数据发送到堆部分可以使其在任何时候都可以访问,无论它是私有的还是公共的,但似乎不可能。
你能解释一下它是如何工作的吗?
(我什至不完全理解class 的工作原理,因此非常感谢详细解释。谢谢!)
【问题讨论】:
-
你认为
private是什么意思? -
private部分中的内容只能由类本身访问。protected部分中的内容也可供派生类访问。public部分中的内容可供任何人访问。通常,accessor 成员函数用于访问私有成员变量。int getID() const { return ID; } -
旁注,您的代码中不需要指针,也不需要
new。 -
@Eljay 不仅是班级本身,班级的frends也可以访问私有的东西。
-
正确,您无法打印或比较
private部分中的数据,除非它是由其自己的类中的函数或友元函数完成的。