c++ - 如何使用 *pointer 从函数中获取第二个值?

标签 c++ pointers console

我有一个函数,我需要从那里获取两个值。函数只能返回一个值。我在某处读到,我可以使用指针来获取第二个值,当我尝试执行此操作时,我收到错误,因此看起来指针值不能超出可见区域。这意味着我只有一个值。如何使用指针从函数中获取第二个值?

最佳答案

某种类型的实例是“一个值”。考虑这个类:

struct foo {
     int bar;
     double moo;
};

现在我可以编写一个返回该类型的一个值的函数:

foo asdf() { 
    foo result;
    result.bar = 42;
    result.moo = 3.14159;
    return result;
}

PS:不要使用指针。可以使用所谓的输出参数,但如果这样做,您应该使用引用而不是指针:

void asdf2(int& bar,int& moo) {
     bar = 42;
     moo = 3.14159;
}

这样调用:

int x = 0;
double y = 0.;
asdf2(x,y);

但是,out参数不太好,因为在 foo f = asdf(); 中与 asdf2(x,y) 相比,函数返回的内容更加明显.

关于c++ - 如何使用 *pointer 从函数中获取第二个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62429636/

相关文章:

c++ - 将 int** 转换为 "pointer to a two-dimensional array of integers with fixed number of elements per column"

c# - 同时在控制台和文件上写入文本

console - 无法在 PyCharm 中使用 IPython 控制台

c++ - 是否返回语句复制值

c++ - 是否有跨平台的方法来禁用 C++ 中已弃用的警告?

c++ - 从非托管 C++ 调用 PowerShell 脚本

c++ - const_cast(this) 性能命中

c++ - 对指针列表进行排序

pointers - 为什么解码到指针变量是不可能的?

c# - 控制台应用程序文本始终在最前面