繁体   English   中英

访问班级的私人成员

[英]Accessing private members of a class

我不熟悉类,因此创建了一个新类来跟踪帐户的不同详细信息,但是我被告知班级的成员应该是私有的,并且应该使用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;
}

您应该有一个朋友运算符重载:

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;
}

这是获取/设置方法的示例:

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方法是否是一个好主意,这是另一个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM