【问题标题】:Accessing private members of a class访问类的私有成员
【发布时间】:2013-09-24 22:36:27
【问题描述】:

我是新的类我创建了一个新类来跟踪帐户的不同详细信息,但是我被告知我的类的成员应该是私有的并使用 getter 和 setter 函数。我看过很多例子,但我似乎无法弄清楚如何从我的主程序访问私人成员。如果我将成员公开,我希望用户为帐户输入不同的参数,它工作得很好我如何添加 getter 和 setter。我班级的私人成员和主要内容是我需要添加的所有其他内容以使其正常工作的唯一东西,但我真的迷路了。我使用向量,因为一旦我让它工作,我将编写一个循环来获取多个帐户的数据,但现在我只是试图获取存储的输入

class account

{  public            
       friend void getter(int x);

   private:
       int a;
       char b;
       int c;
       int d;
};

using namespace std;

void  getter (int x)
{

}

int main()
{
  vector <account> data1 (0);
  account temp;

  cin>>temp.a>>temp.b>>temp.c>>temp.d;
  data1.push_back(temp);

  return 0;
}

【问题讨论】:

  • 谁告诉你要使用 getter 和 setter?

标签: c++


【解决方案1】:

你应该有一个友元运算符重载:

class account
{
    friend std::istream& operator>> (std::istream &, account &);
public:
    // ...
};

std::istream& operator>> (std::istream& is, account& ac)
{
    return is >> ac.a >> ac.b >> ac.c >> ac.d;
}

int main()
{
    account temp;

    std::cin >> temp;
}

【讨论】:

  • @JesseWashington 像我一样做std::cin &gt;&gt; temp;
  • 好的,我知道什么是运算符过载,并且我对代码的作用非常了解。我熟悉使用数据类型末尾的 & 来通过引用传递它们,但为什么它本身就是 ex。 (std::istream &, 账户 &);但后来它(std::istream& is, account& ac)。哦,顺便说一句,它现在可以工作了,谢谢
  • @JesseWashington 很好,我很高兴它能正常工作。第一个只是函数的原型,因此参数名称是可选的。我只在需要使用参数时(例如在实现函数时)给出参数名称。
  • 所以我可以将 operator>> 更改为 +,例如 std::istream& operator+ (std::istream& is, account& ac) { return is >> ac.a >> ac.b >> ac .c >> a.d; } 然后使用 cin+temp;
  • 我知道仅仅尝试学习如何使用这些新东西是不切实际的
【解决方案2】:

以下是 get/set 方法的示例:

class account

{  public            
       int getA() const { return a; }
       void setA(int new_value) { a = new_value; }
       int getB() const { return b; }
       void setB(int new_value) { b = new_value; }
       int getC() const { return c; }
       void setC(int new_value) { c = new_value; }
       int getD() const { return d; }
       void setD(int new_value) { d = new_value; }

   private:
       int a;
       char b;
       int c;
       int d;
};

从您将使用的主目录:

int main()
{
  vector <account> data1 (0);
  account temp;
  int a,b,c,d;

  cin >> a >> b >> c >> d;
  temp.setA(a);
  temp.setB(b);
  temp.setC(c);
  temp.setD(d);
  data1.push_back(temp);

  return 0;
}

注意:在这种情况下使用 get/set 方法是否是一个好主意是另一个问题。

【讨论】:

  • 那么它如何与 cin>>temp.a>>temp.b>>temp.c>>temp.d 一起工作;我仍然收到错误无法访问私人成员 a b c 和 d;
  • @JesseWashington:我添加了一个例子。
  • -1。您没有必须编写 get/set 方法。请不要鼓励这种编程风格。重载 operator&gt;&gt; 以获得更好的封装。
  • 说真的,如果你正在这样做,就把该死的事情公之于众。拯救你的手腕。
  • @Tjarmws 套用 Scott Meyers 的话说:“坦率地说,如果你和那些告诉你使用 getter 和 setter 的人一起出去玩,你需要重新考虑你的社交圈。”
猜你喜欢
  • 1970-01-01
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2020-01-19
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多