首页 > 解决方案 > 为什么这个没有类型的函数仍然有效?

问题描述

为什么即使我声明了一个没有类型的函数,我也没有收到错误消息?

如果默认情况下返回类型被接受为某些类型,那么编写这样的代码是否健康?

如果它已经通过编译器功能像这样工作,那么为什么我们甚至需要为函数编写void呢?

注意:我使用的 Code::Blocks 有一个遵循 c++11 std 的 gnu 编译器,如果它与它有任何关系的话。

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

ProfitDetermine (string str="")
{
    int profit=0, outcome=0, income=0, sales=0;
    int numberofhc=10, insur=1000000, hccost=2000000, price=3000000;
    stringstream (str) >> sales;

    outcome = (numberofhc * (insur + hccost));
    income = (sales*price);
    profit = income - outcome;
    cout << "profit is " << profit <<endl;

    if (profit < 0)
        cout << "lost\n";
    else if (profit==0)
        cout << "even\n";
    else
        cout << "profit\n";
}

int main()
{
    string sales="";
    cout << "enter the number of sales\n";
    getline(cin,sales);
    stringstream (sales) >> sales;

    while (sales!="quit") {
    ProfitDetermine(sales);
    cout << "\n\nEnter the number of sales\n";
    cin >> sales;
    }

}

标签: c++function-declaration

解决方案


在 C++ 中,根据 ISO C++ 声明没有类型的函数是错误的,但您可以使用“-fpermissive”标志忽略此错误。您的编译器可能会使用此标志来忽略标准编码错误,将它们降级为警告。在声明函数时,您应该始终至少使用 void 类型,以便您的代码符合标准并且每个程序员和编译器都可以理解。


推荐阅读