首页 > 解决方案 > 非标准语法;使用 '&' 创建指向成员 C++ 的指针

问题描述

我在运行我的一小段代码时遇到问题。我有一个从用户输入读取温度的向量。我想稍微处理一下数据。给出这是哪一天(炎热的一天,夏天的一天,等等......),哪一天是最热的。但是每次我想用函数 maxNumber 获得最高温度时,我都会得到 2 个我不明白的错误:

non-standard syntax; use '&' to create a pointer to member

"! =": Function overload cannot be resolved

请帮忙!非常感谢

代码:

#include <iostream>
#include <vector>

std::string klimaTag(float a) {
    if (a >= 25 and a < 30) {
        return "Sommertag";
    }
    else if (a >= 30 and a < 35) {
        return "Heißer Tag";
    }
    else if (a >= 35) {
        return "Wüstentag";
    }
    else {
        return "Normaltag";
    }
}

float maxNumber(std::vector<float> &a) {
    float current_max = 0;
    for (int i = a.begin; i != a.end; i++) {
        if (a.at(i) > current_max) {
            current_max = a.at(i);
        }
        return current_max;
    }
}


int main()
{
    std::vector<float> temperatures;
    float current_temp;
    
    for (int i = 0; i < 5; i++) {
        std::cout << "Hoechsttemp für Tag " << i << " eingeben: ";
        std::cin >> current_temp;
        temperatures.push_back(current_temp);
    }

    for (int i = 0; i < 5; i++) {
        std::cout << "Tag " << i +  1 << " ist ein " << klimaTag(temperatures.at(i)) << std::endl;
    }
    std::cout << maxNumber(temperatures);
}

标签: c++functionpointersvector

解决方案


首先begin()and end()are 方法,所以你得到这个错误是因为你试图引用一个函数,所以它应该需要一个地址运算符。

其次是返回一个begin()而不是一个索引,并且您正在清除尝试访问类似的索引。end()iterator

第三件事是你总是在第一个周期之后返回,因为你的返回在里面并且应该在外面。

要正确循环,您的数组足以使用 for range 循环

float maxNumber(std::vector<float> &a) {
    float current_max = 0;
    for(const auto& element : a) {
     if(element > current_max){
            current_max = element; 
        }
    }
    return current_max;
}

如果您想使用旧方式,您可以随时使用

float maxNumber(std::vector<float> &a) {
    float current_max = 0;
    for(int i=0; i<a.size(); ++a) {
     if(a.at(i) > current_max){
            current_max = a.at(i); 
        }
    }
    return current_max;
}

推荐阅读