c++中友元函数显示错误
Friend function in c++ showing error
#include <iostream>
using namespace std;
class time{
int date,month,year;
public:
void gettime(){
cout<<"enter the (date/month/year)n";
cin>>date>>month>>year;
}
void show(){
cout<<"Your age is:-"<<date<<month<<year;
}
friend time Add(time a1,time a2);
};
time Add(time a1,time a2){
time temp;
if(a2.date<a1.date)
{
a2.date=a2.date+30;
temp.date=a2.date-a1.date;
a2.month=a2.month-1;
}
else
temp.date=a2.date-a1.date;
if(a2.month<a1.month)
{
a2.month=a2.month+12;
temp.month=a2.month-a1.month;
a2.year=a2.year-1;
}
else
temp.month=a2.month-a1.month;
temp.year=a2.year-a1.year;
return (temp);
}
int main()
{
time a1,a2,t3;
a1.gettime();
a2.gettime();
t3=Add(a1,a2); //this is the friend function
t3.show();
return 0;
}
这可以在Dev c++中工作,但不能在gcc和任何其他编译器中工作。
age.cpp:17:1: error: ‘time’ does not name a type
time Add(time a1,time a2){
^
age.cpp: In function ‘int main()’:
age.cpp:42:7: error: expected ‘;’ before ‘a1’
time a1,a2,t3;
^
age.cpp:43:2: error: ‘a1’ was not declared in this scope
a1.gettime();
^
age.cpp:44:2: error: ‘a2’ was not declared in this scope
a2.gettime();
^
age.cpp:45:2: error: ‘t3’ was not declared in this scope
t3=Add(a1,a2);
^
age.cpp:45:14: error: ‘Add’ was not declared in this scope
t3=Add(a1,a2);
^
iostream
正在拉入time.h
或ctime
。这是在全局命名空间和/或std
命名空间中声明函数time_t time(time_t *t);
,导致名称冲突。
要解决这个问题,请重命名您的类,或者在您自己的命名空间中定义它。
我还建议远离using namespace std;
,以避免其他名称冲突或歧义,尽管它不是您在这种情况下问题的原因。
相关文章:
- 显示错误输出的简单数组排序程序
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- Clion显示错误,但可以使用Cmake成功构建代码
- 代码使用向量成功运行,但使用数组显示错误
- SDL 映像:无法打开映像,仅显示错误消息
- 为什么将指针重新分配给 1D 数组的 char 时显示错误,但 2D 数组工作正常?
- 与clang++一起使用的VS代码在构建良好的C++文件中显示错误
- 编译器没有显示错误,但我没有得到任何输出.怎么了?
- PPM 颜色显示错误
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- is_permutation方法从 #include<algorithm> 显示错误的输出
- 为什么使用与父级声明的 std::function 在与子级一起使用时会显示错误?
- 我的代码厨师提交显示错误的结果
- 显示错误"std_lib_facilities.h"
- 为什么C++显示错误的数字?
- Android (ART) 崩溃并显示错误 JNI 在应用程序中检测到错误:jstring 是无效的本地引用
- 这是我的 .h 文件的一些错误,当我在其中包含我的类模板时,它显示 [错误] 未终止 #ifndef
- c++ IF 语句执行,但添加 ELSE 会显示错误
- 内核.cpp在制作 kernel.o 时显示错误和 Makefile 错误
- C++代码编译,但在 Zorin OS 上运行时显示错误