c++ - C++:关于方法和“已经有正文”错误的基本问题
问题描述
我正在开发一个需要大量秒数的程序,并试图将它们分解为天、小时、分钟和秒。作为 C++ 的新手,我试图将这个问题分成 3 种方法:主要(从用户那里获取秒数,并将结果传递给“计算”)、计算(尝试将值除以天/小时/分钟,然后通过这些方法)到“结果”上)和结果(打印出结果)。
目前我遇到了编译器返回的问题:
错误 C2084:函数 'void 计算(__int64)' 已经有一个主体
除此之外,我一直在环顾四周,注意到很多人在处理这些东西时使用“头文件”;所以我的第二个问题是这是必要的,有没有办法避免它(我只需要提交 1 个 .cpp 文件,所以我的主文件之外的任何东西都必须是不可能的)。
以下是我到目前为止的代码,
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
//method declarations
void calculation(long long int value) {};
void results(int days, int hours, int mins, int secs) {};
int main()
{
//Declaration
long long int seconds;
//user prompt
cout << "Enter seconds" << endl;
cin >> seconds;
//check for valid input
if (seconds > 0)
{
cout << endl << "Total seconds: " << seconds;
calculation(seconds);
}
else
{
cout << "Total seconds must be greater than zero";
}
}
void calculation(long long int value)
{
//divisor values
const int secToDay = 86400;
const int secToHour = 3600;
const int secToMin = 60;
//calculated vars
int d, h, m, s;
//calculating if there are any days in this
d = value / secToDay;
if (d != 0)
value -= (secToDay * d);
//calculating if there's any hours
h = value / secToHour;
if (h != 0)
value -= (secToHour * h);
//calculating minutes
m = value / secToMin;
if (m != 0)
value -= (secToMin * m);
//whatever's left over goes to seconds
s = value;
results(d, h, m, s);
}
void results(int days, int hours, int mins, int secs)
{
cout << days << " day(s)" << endl;
cout << hours << " hours(s)" << endl;
cout << mins << " minute(s)" << endl;
cout << secs << " second(s)" << endl;
}
解决方案
{}
从您的声明中删除。
定义
void results(int days, int hours, int mins, int secs) {};
这称为函数定义。
c++ 函数定义告诉编译器函数的实际主体。函数定义也是声明。
认为这与
void results(int days, int hours, int mins, int secs)
{
}
;
注意:函数定义后不需要分号
宣言
void results(int days, int hours, int mins, int secs);
这是一个函数声明。
函数声明告诉编译器函数的名称、返回类型和参数。函数声明不是定义。
要让您的代码正确编译,请将您的定义更改为声明。
简而言之,删除{}
.
推荐阅读
- javascript - 对象作为 React 子对象无效(找到:带有键 {children} 的对象)。如果您打算渲染一组孩子,请改用数组
- node.js - AWS Lambda + Firestore 数据库:add() 不在集合中插入文档数据
- spring-boot - HashiCorp Vault ldap.urls 的多个值(url 列表)
- postgresql - 在 Postgres 中将 JSON 列拆分为多个列
- javascript - 在多个 javascript 数组中查找匹配项并输出重复数组
- sql - 改进 SQL Server 中物理表的选择查询
- c++ - CGAL insert_constraint
- java - JSONObject 中的嵌套数组返回为空(org.json)
- c# - 如何在不使用 new() 方法的情况下设置属性值使用另一个属性?
- flutter - 如何在分组列表中创建网格