关于友元在类外定义还是在类内定义的问题
昨天看到论坛里一篇关于重载operator <<的帖子,我试了下,有一个问题不明白,以前倒没注意过,代码如下请各位看一下:
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
int key;
string name;
friend ostream & operator << (ostream &s,const student &k)
{
cout << "in";
return s;
}
friend void ff(student &s)
{
cout<<s.name<<endl;
};
student(){};
virtual ~student(){};
student(string &s);
};
student::student(string &s)
{
name=s;
}
ostream & operator << (ostream &s,const student &k)
{
cout<<"out";
//printf("name=%s,key=%d\n", k.name, k.key);
//printf("name=%s,key=%d\n", "k.name", 1);
return s;
}
void ff(student &s)
{
cout<<"out"<<endl;
}
void main()
{
string t="tim";
const student s1(t);
cout<<s1<<endl;
}
出现两个错误,一个是说函数ff已经有定义了,另一个是说operator<< is ambiguous,两个函数都是友元函数,怎么会有上面两个不同的错误? 我把类外面的operator<<参数去掉const就会少一个错误了,这应该是函数解析对了,但为什么函数ff没有出现类似的问题呢?而是说已经定义过了呢?是不是友元函数实现应该放在类定义之内?
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
int key;
string name;
friend ostream & operator << (ostream &s,const student &k)
{
cout << "in";
return s;
}
friend void ff(student &s)
{
cout<<s.name<<endl;
};
student(){};
virtual ~student(){};
student(string &s);
};
student::student(string &s)
{
name=s;
}
ostream & operator << (ostream &s,const student &k)
{
cout<<"out";
//printf("name=%s,key=%d\n", k.name, k.key);
//printf("name=%s,key=%d\n", "k.name", 1);
return s;
}
void ff(student &s)
{
cout<<"out"<<endl;
}
void main()
{
string t="tim";
const student s1(t);
cout<<s1<<endl;
}
出现两个错误,一个是说函数ff已经有定义了,另一个是说operator<< is ambiguous,两个函数都是友元函数,怎么会有上面两个不同的错误? 我把类外面的operator<<参数去掉const就会少一个错误了,这应该是函数解析对了,但为什么函数ff没有出现类似的问题呢?而是说已经定义过了呢?是不是友元函数实现应该放在类定义之内?
...全文
相关推荐
(源码)基于C语言和STM32的电梯系统模拟.zip
# 基于C语言和STM32的电梯系统模拟 ## 项目简介 本项目基于C语言和STM32框架实现了一个电梯系统模拟。项目包含电梯调度算法的库实现、命令行客户端界面以及用于在STM32微控制器嵌入式平台验证算法的STM32CubeIDE项目。 ## 项目的主要特性和功能 1. 具备电梯调度算法库,可模拟电梯的运行。 2. 提供基于控制台的用户界面程序,便于模拟电梯系统运行。 3. 提供STM32CubeIDE项目,用于在嵌入式平台验证算法。 ## 安装使用步骤 1. 环境准备确保已安装C编译器和STM32CubeIDE开发环境。 2. 代码下载从项目仓库下载源代码。 3. 编译与验证在STM32CubeIDE中导入项目,编译并下载到STM32微控制器上以验证算法。
stm32变频器,stm32变频器程序,C,C++源码.zip
stm32变频器,stm32变频器程序,C,C++源码.zip
8*8点阵屏来模拟显示电梯运行楼层
用keil 5和proteus完成的单片机课设作业,现分享出来
ele2.rar_单片机开发_C/C++_
电梯比赛控制程序,通过STM32进行控制,包括人机界面
能量回收装置_能量回馈_e题能量回收_回收_电赛、C_电子设计大赛_
18年全国电子设计大赛E题 采用STM32使用C语言来完成对能量装置的回馈


