0

我创建了结构Route.h

#include "stdafx.h"
using namespace std;

struct Route {
    string startPoint;
    string endPoint;
    int number;
};

我需要将这个结构传递给函数。我使用了参考:

void CreateRoute(Route &route)
{
  int start = rand() % 10;
  int end = rand() % 10;

  if (start == end)
  {
    while(true)
    {
      end = rand()%10;
      if(end != start) break;
    }
  }

  route.startPoint = SetPoint(start);
  route.endPoint = SetPoint(end);
  route.number = SetNumber();
}

但似乎使用指针是更好的方法,但我不知道如何使用指针?

4

3 回答 3

3

在这种情况下,为什么不简单地返回一个新构造的对象呢?

struct route
{
    std::string start_point;
    std::string end_point;
    int number;
};

route make_random_route()
{
    route r;

    int start = std::rand() % 10;
    int end = std::rand() % 10;

    while ( start == end) {
        end = std::rand() % 10;
    }

    r.start_point = make_point(start);
    r.end_point = make_point(end);
    r.number = make_number();

    return r;
}

它微不足道,并且移动没有副本。

于 2013-10-16T10:18:32.640 回答
2

but it seems the using of pointers is the better way to do it

C++ 开始引用的原因之一是为了避免处理指针、箭头和大量括号的麻烦。

您可以轻松地将其转换为使用指针类型,但 ref 类型更简洁。

void CreateRoute(Route* route);

将是您的声明,您可以使用

Route route;
CreateRoute(&route);
于 2013-10-16T10:02:27.437 回答
1

我认为你必须提高你的 C++ 基础。下面是我的简单回答。

void CreateRoute(Route *route)
{
if (route == NULL)
    return;

int start = rand()%10;
int end = rand()%10;

if (start == end)
{
    while(true)
    {
        end = rand()%10;
        if(end != start) break;
    }
}

route->startPoint = SetPoint(start);
route->endPoint = SetPoint(end);
route->number = SetNumber();
}
于 2013-10-16T10:05:14.547 回答