c++中如何从get函数返回多个值
how to return multiple values from get function in c++
我基本上在私有类中传递两个参数,我试图在我的主函数中访问这两个参数。由于我将这两个参数设为私有,所以我使用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;
}
可以返回单个值,也可以将参数作为值-结果参数(指针或引用),也可以返回包含参数的结构。您很可能只需要分别访问a
或b
,那么为什么不直接创建两个访问器
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;
};
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数