C 标识符未定义

新手上路,请多包涵

我是 C++ 新手,我不明白为什么会出现此错误。在 5 个类似的语句中,有 3 个标记错误,但其他两个没问题。错误在主函数中。

     #include <iostream>
using namespace std;

// Function declaration
void getGallons(int wall);
void getHours(int gallons);
void getCostpaint(int gallons, int pricePaint);
void getLaborcharges(int hours);
void getTotalcost(int costPaint, int laborCharges);

// Function definition
void getGallons(int wall)
{
    int gallons;

    gallons = wall / 112;

    cout << "Number of gallons of paint required: " << gallons << endl;

}

// Function definition
void getHours(int gallons)
{
    int hours;

    hours = gallons * 8;

    cout << "Hours of labor required: " << hours << endl;

}

// Function definition
void getCostpaint(int gallons, int pricePaint)
{
    int costPaint;

    costPaint = gallons * pricePaint;

    cout << "The cost of paint: " << costPaint << endl;
}

// Function definition
void getLaborcharges(int hours)
{
    int laborCharges;

    laborCharges = hours * 35;

    cout << "The labor charge: " << laborCharges << endl;
}

// Funtion definition
void getTotalcost(int costPaint, int laborCharges)
{
    int totalCost;

    totalCost = costPaint + laborCharges;

    cout << "The total cost of the job: " << totalCost << endl;
}

// The main method
int main()
{
    int wall;
    int pricePaint;

    cout << "Enter square feet of wall: ";
    cin >> wall;

    cout << "Enter price of paint per gallon: ";
    cin >> pricePaint;

    getGallons(wall);

    getHours(gallons); // error here

    getCostpaint(gallons, pricePaint);

    getLaborcharges(hours); // error here

    getTotalcost(costPaint, laborCharges); //error here

    return 0;

}

本课的重点是在代码中使用函数和传递参数。我不应该使用全局变量。如果您有更好的方法来做到这一点,请分享。

原文由 hcas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 931
1 个回答

减少到三行(其他错误类似):

 int wall;
getGallons(wall);
getHours(gallons); // error here

虽然定义了 wall ,但没有定义 gallons 。你想从哪里得到 gallons ?结果隐藏在另一个函数的深处。你想怎么把它从那里弄出来?

好吧,你需要一个返回值:

   int getGallons(int wall)
//^^^ !
{
     int gallons = wall / 112;
     // ...
     return gallons; // !
}

这样,您可以像这样使用您的函数:

 int gallons = getGallons(wall);
// now gallons is defined and you can use it:
getHours(gallons);

类似地用于其他函数和变量。

通常,在同一个函数中混合逻辑(计算)和输出 并不是 一个好主意。所以我宁愿将写入控制台移动到 main 函数:

 int getGallons(int wall) { return wall / 112; }
int getHours(int gallons) { return gallons * 8; }

int wall;
std::cin >> wall;
int gallons = getGallons(int wall);
std::cout << ...;
int hours = getHours(gallons);
std::cout << ...;

注意?现在所有输入/输出都处于同一水平……

旁注:如果在定义之前不使用函数,则无需在定义函数之前声明它们:

 //void f(); // CAN be ommitted
void f() { };
void g() { f(); }

反例:

 void f();
void g() { f(); } // now using f before it is defined, thus you NEED do declare it
void f() { };

如果您仍然想保留声明,那是一个风格问题(但在管理不同编译单元中的代码时会变得很重要,因为您将在头文件中拥有声明——您将在下一课中很快遇到)。

原文由 Aconcagua 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题