【问题标题】:Why is my function not returning type Point?为什么我的函数不返回类型点?
【发布时间】:2019-10-10 22:13:47
【问题描述】:

我正在尝试学习 C++ 语法,对于下面的这个函数 close_coin,我在 closest_coin 函数中的 return result 行中获得了“使用未声明的标识符”。为什么我在赋值变量result时在if语句中声明了类型会出现这种情况?

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

class Point{
    public:
        int x,y;
        Point(int x_position, int y_position){
            x = x_position;
            y = y_position;
        }
        int calculate_distance(Point other_point);
};

int Point::calculate_distance(Point p2){

    int x_distance = abs(x-p2.x);
    int y_distance = abs(y-p2.y);
    int result = x_distance-y_distance;

    return result;
}

Point closest_coin(Point your_position, vector<Point> coin_positions){
    int closest_distance = -1;
    int distance;

    for (Point coin : coin_positions){
        distance = your_position.calculate_distance(coin);

        if (distance>closest_distance){
            Point result = coin;
            closest_distance = distance;
        }
    }

    return result;
}

【问题讨论】:

  • 看看你在哪里声明 Point resultreturn result; 在哪里。这些是不同的范围
  • 所以我需要添加“点结果;”在最接近的_coin(){ } 括号内?

标签: c++


【解决方案1】:

当我在 if 语句中声明类型时

当您在{} 中声明任何内容时,该变量仅在那里有效。如果您出于同样的原因在 if 之外但在 for 循环内声明它,它也不起作用。

您可以只在closest_coin 函数的开头声明result 变量,并且只在if 内赋值。

注意:您的Point 类没有默认构造函数。因此,您必须在声明时设置一些值。你的closest_coint 方法变成了

Point closest_coin(Point your_position, vector<Point> coin_positions){
    int closest_distance = -1;
    int distance;

    Point result(0,0);
    for (Point coin : coin_positions){
        distance = your_position.calculate_distance(coin);

        if (distance>closest_distance){
            result = coin;
            closest_distance = distance;
        }
    }

    return result;
}

【讨论】:

  • 无论如何在这里定义结果为Point result; 而不初始化类?我知道这会引发错误,正如我在这里所写的那样。仅供参考,谢谢。编辑:没有完全阅读您的答案,默认构造函数..将阅读它们。
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 2018-11-26
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
相关资源
最近更新 更多