c++中如何从get函数返回多个值

how to return multiple values from get function in c++

本文关键字:返回 函数 get c++      更新时间:2023-10-16

我基本上在私有类中传递两个参数,我试图在我的主函数中访问这两个参数。由于我将这两个参数设为私有,所以我使用get和set函数来访问这些参数,但是我不能从get函数返回两个值。请帮帮我。上一篇文章问了同样的问题,但这次被问到面向对象的概念。

class FirstClass{
  public:
    void setName(int x,int y){
        a = x;
        b = y;
}
    int getName(){
    return a,b;
     }
  private:
    int a,b;
};

使用引用:

int getName(int &a1, int &b1) {
    a1 = a;
    b1 = b;
}

或使用两个函数:

int getA() {
    return a;
}
int getB() {
    return b;
}

可以返回单个值,也可以将参数作为值-结果参数(指针或引用),也可以返回包含参数的结构。您很可能只需要分别访问ab,那么为什么不直接创建两个访问器

呢?
int getNameA(){
  return a;
}
int getNameB(){
  return b;
}

访问器/mutator或getter/setter只能获取/设置一个值。你的代码应该是这样的:

class FirstClass{
  public:
  FirstClass(int x,int y){ //constructor, initialize the values
    a = x;
    b = y;
}
  int getA(){
  return a;
 }
  int getB(){
  return b;
 }
  int setA(const int newVal){ //using const is a good practice
   a=newVal;
 }
  int setB(const int newVal){ //using const is a good practice
   b= newVal;
 }
 // you can use reference/pointer to *obtain* multiple values, although it is rarely used and seems inappropriate in your code
 void getBoth(int& aRef, int& bRef){
   aRef = a;
   bRef = b;
}

  private:
  int a,b;
};