【问题标题】:C++ How to pass two structs from function?C ++如何从函数传递两个结构?
【发布时间】:2018-08-20 04:13:10
【问题描述】:

这里是主函数ex1-1.cpp

#include <iostream>
#include "ex1-1.h"
using namespace Complex;

int main(int argc, char *argv[])
{

Cplex a={0.0,0.0}, b={0.0,0.0},c={0.0,0.0}, d={0.0,0.0}; 
// use struct named Cplex under namespace Complex
ReadTextFile(argv[1], a, b);// process text file


std::cout<<a.real<<std::showpos<<a.image<<std::endl;
std::cout<<b.real<<std::showpos<<b.image<<std::endl;

return 0;
} 

一个头文件 ex1-1.h

#include <iostream>
#include <fstream>
namespace Complex 
{
    typedef struct
{
    double real;
    double image;
}Cplex;


Cplex ReadTextFile(char argv[],Cplex a,Cplex b);

}

一个用于函数 ex1-1-function.cpp

#include<iostream>
#include<fstream>
#include<iomanip>
#include "ex1-1.h"
namespace Complex
{

Cplex ReadTextFile(char argv[],Cplex a,Cplex b)
{

    std::ifstream fin;
    fin.open("complex.txt");

    char i;
    fin>>a.real>>a.image>>i;
    fin>>b.real>>b.image>>i;
    std::cout<<std::noshowpos<<a.real<<std::showpos<<a.image<<"i"<<std::endl;
    std::cout<<std::noshowpos<<b.real<<std::showpos<<b.image<<"i"<<std::endl;

    return (a,b);
};

}

文本文件 complex.txt 如下所示

1.5+6i
-2-10i 

我尝试定义一种称为 Cplex 的结构,包括两个成员,real 和 image

声明 Cplex a 和 Cplex b

然后使用函数ReadTextFileread(argv[1],a,b)读取两个复数并存储在结构a和b中

然后同时返回 a 和 b

但是无论我怎么尝试main函数都只能读取b而不是两者

如何一次将两个结构传递给主函数?

或者我应该使用 Array 来包含两个结构然后传递它?

【问题讨论】:

  • 题外话:你为什么把argv传给ReadTextFile
  • 我不太确定。也许复杂的 a 和 b 应该在 argv 数组中返回?

标签: c++ function oop struct


【解决方案1】:

您可以使用std::pair 将两个值耦合在一起:

std::pair<Cplex> ReadTextFile(char argv[])
{
    Cplex a, b;
    ...
    return { a, b };
};

然后像这样使用它们:

#include <tuple>
...
Cplex a, b;
std::tie(a, b) = ReadTextFile(argv);

请注意,std::tie 仅在 C++11 之后可用。

或者如果你可以使用 C++17,那么使用结构化绑定会更简单:

auto [a, b] = ReadTextFile(argv);

【讨论】:

  • 好答案!如果您最终可能得到两个以上的复数,请考虑使用 std::vector&lt;Cplex&gt; 作为返回值。
【解决方案2】:

在 C 和 C++ 中,您只能从函数返回一个值。

改为使用按引用传递来传递结构“a”和“b”,然后在函数中填充值。

声明:

void ReadTextFile(char argv[],Cplex &a,Cplex &b);

定义:

void ReadTextFile(char argv[],Cplex& a,Cplex& b)
{

    std::ifstream fin;
    fin.open("complex.txt");

    char i;
    fin>>a.real>>a.image>>i;  // values filled here can now be read in the caller i.e main.
    fin>>b.real>>b.image>>i;
    std::cout<<std::noshowpos<<a.real<<std::showpos<<a.image<<"i"<<std::endl;
    std::cout<<std::noshowpos<<b.real<<std::showpos<<b.image<<"i"<<std::endl;

    return;
};

希望这会有所帮助。

【讨论】:

  • 可能我会这样做,但另一种可能性是返回std::pair
猜你喜欢
  • 2020-10-06
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多