c++ - 为什么这个没有类型的函数仍然有效?
问题描述
为什么即使我声明了一个没有类型的函数,我也没有收到错误消息?
如果默认情况下返回类型被接受为某些类型,那么编写这样的代码是否健康?
如果它已经通过编译器功能像这样工作,那么为什么我们甚至需要为函数编写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++ 中,根据 ISO C++ 声明没有类型的函数是错误的,但您可以使用“-fpermissive”标志忽略此错误。您的编译器可能会使用此标志来忽略标准编码错误,将它们降级为警告。在声明函数时,您应该始终至少使用 void 类型,以便您的代码符合标准并且每个程序员和编译器都可以理解。
推荐阅读
- node.js - TypeDI 和 Lambda/无服务器
- android - MPandroidGraph 不显示片段中的数据,只有蓝色圆圈
- discord.js - 尝试使用 java 脚本制作不和谐机器人时出错
- node.js - Express - 验证补丁请求
- javascript - Jest 尝试报告未经测试的 JSON 文件的覆盖率并抛出错误
- c# - 使用 .NET 核心识别 Winform 应用程序显示的 MessageBox 窗口类型
- css - 图像在顺风的响应视图中缩小
- python - Python - 是否有一种简写方式来表示“如果(某些条件),则设置 var = [...],否则,设置 var = [其他内容]”?
- php - 如何将模型添加到 laravel 通知并用 eloquent 访问它?
- php - 如何通过usb端口通信从arduino将串行数据写入phpmyadmin