我创建了结构 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();
}
但似乎使用指针是更好的方法,但我不知道如何使用指针?
答案 0 :(得分: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;
}
它的琐碎,并且移动没有副本。
答案 1 :(得分: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);
答案 2 :(得分: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();
}