【问题标题】:How can i access to any data that is in private section of class?我如何访问课程私有部分中的任何数据?
【发布时间】: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;
}

这是我正在尝试的简单代码。

我想访问我存储在向量中的数据。

我认为可以通过使用 -&gt; 来访问它,就像 struct 的向量一样,但我不能。所以我想知道如何在类中加载数据。

此外,我认为使用new 将数据发送到堆部分可以使其在任何时候都可以访问,无论它是私有的还是公共的,但似乎不可能。

你能解释一下它是如何工作的吗?

(我什至不完全理解class 的工作原理,因此非常感谢详细解释。谢谢!)

【问题讨论】:

  • 你认为private是什么意思?
  • private 部分中的内容只能由类本身访问。 protected 部分中的内容也可供派生类访问。 public 部分中的内容可供任何人访问。通常,accessor 成员函数用于访问私有成员变量。 int getID() const { return ID; }
  • 旁注,您的代码中不需要指针,也不需要new
  • @Eljay 不仅是班级本身,班级的frends也可以访问私有的东西。
  • 正确,您无法打印或比较private部分中的数据,除非它是由其自己的类中的函数或友元函数完成的。

标签: c++ class private


【解决方案1】:

类定义之外的代码无法访问private 变量。 (friend 有例外)

ptr-&gt;ID 不起作用,因为main 在类定义之外。

这可以通过使用 getter 方法来解决。

#include <iostream>
#include <vector>

using namespace std;

class Test
{
private:
    int _ID;
    string _name;

public:
    int ID() {return _ID;}
    string name() {return _name;}
    Test(int param_ID, string param_name);
};

Test::Test(int param_ID, string param_name)
{
    _ID = param_ID;
    _name = param_name;
}

int main()
{
    vector<Test *> test_vect;

    Test *ptr = new Test(100, "John");

    test_vect.push_back(ptr);

    cout << ptr->ID() << endl;

    return 0;
}

上面的例子展示了getter方法ID()name(),它们分别返回数据成员_ID_name

ID() 被允许访问_ID,因为ID() 是类定义的一部分。允许name() 访问_name,因为name() 是类定义的一部分。

注意:我仍然认为这段代码有缺陷,因为它在堆上创建了一个新对象,但没有删除它。您还应该查找关键字 newdelete 以了解它们如何协同工作。

【讨论】:

    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多