gpt4 book ai didi

c++ - 我可以将什么用作 NULL 结构?

转载 作者:行者123 更新时间:2023-11-28 03:06:46 25 4
gpt4 key购买 nike

我想编写一个循环,通过同一个结构(在我的例子中名为 edg)的几个实例,由某个函数从一个邻居到另一个邻居迭代,直到它返回一个表示 STOP 的元素。我尝试使用 NULL 返回对其进行编码,但它不起作用。我能用什么?

这里有一些代码解释它可能比我之前的话更准确:我的结构:

struct edg{
int i,j,k;
edg(int a, int b, int c){
i = a; j = b; k = c; //I'm adding a constructor to it
}
}

我的迭代函数:

edg neighbour(edg temp){
if(temp satisfies certain criterias){ return edg(new coordinates);}
else{ return NULL;}
}

我的循环:

while(my_edg!=NULL){
my_edg = neighbour(my_edg);
}

我想我可以选择一个 edg 的特定值将其定义为拒绝,并在我的循环中替换为:

while(my_edg!=edg_marked_as_rejection)

但是还有其他方法吗?

最佳答案

注意你的函数:

edg neighbour(edg temp){
if(temp satisfies certain criterias){ return edg(new coordinates); }
else{ return NULL; }
}

按值返回 edg 的实例,因此尝试 return NULL; 是无效的(除非您定义了一些自定义转换)。 NULL 是通过指针传递/返回时的可能值,在这种情况下可能意味着将此函数的原型(prototype)更改为:

edg* neighbour(edg temp) { ... }

然而,基于语义,通过引用传递并返回指示成功的标志会更合理:

bool neighbour(const edg& temp, edg& result) {
if (...) {
result = ...;
return true;
}
return false;
}

或者如果您的条件if(temp satisfies certain criterias)应该在大多数情况下得到满足,而未满足这些条件是一种异常(exception)状态,您还可以考虑抛出异常(而不是返回 NULL)。

第三个选项可能是实现一个NULL 对象设计模式,这意味着标记为“无效”的edg 实例将被构造并返回,调用者将执行类似:

edg n = neighbour(tmp);
if (!n.isValid()) {
...
}

关于c++ - 我可以将什么用作 NULL 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com