一个类的成员函数作为另一个类的友元函数解决方案
一个类的成员函数作为另一个类的友元函数
#include<iostream>
//#include<string>
using namespace std;
class A;
class B
{
public:
void put(const A& a)
{
cout<<a.m_str<<endl;
}
private:
};
class A
{
public:
A(){m_str="";}
A(string str): m_str(str){}
//friend class B;
friend void B::put(const A&);
private:
string m_str;
};
int main()
{
A a="friend";
B b;
b.put(a);
return 0;
}
c++学习新手,学习到友元函数时,想自己写个例子来测试一下,可是就是编译不过,以下是编译提示
D:\my c++\0609\friend\friend.cpp(11) : error C2027: use of undefined type 'A'
D:\my c++\0609\friend\friend.cpp(4) : see declaration of 'A'
D:\my c++\0609\friend\friend.cpp(11) : error C2228: left of '.m_str' must have class/struct/union type
------解决方案--------------------
------解决方案--------------------
如果放在A类的上面的话,因为该函数要输出A类的数据,而此时还不知到A类的具体信息,所以系统会报错。
#include<iostream>
//#include<string>
using namespace std;
class A;
class B
{
public:
void put(const A& a)
{
cout<<a.m_str<<endl;
}
private:
};
class A
{
public:
A(){m_str="";}
A(string str): m_str(str){}
//friend class B;
friend void B::put(const A&);
private:
string m_str;
};
int main()
{
A a="friend";
B b;
b.put(a);
return 0;
}
c++学习新手,学习到友元函数时,想自己写个例子来测试一下,可是就是编译不过,以下是编译提示
D:\my c++\0609\friend\friend.cpp(11) : error C2027: use of undefined type 'A'
D:\my c++\0609\friend\friend.cpp(4) : see declaration of 'A'
D:\my c++\0609\friend\friend.cpp(11) : error C2228: left of '.m_str' must have class/struct/union type
------解决方案--------------------
#include<iostream>
#include<string>
using namespace std;
class A;
class B
{
public:
void put(const A& a);
};
class A
{
public:
A()
{
m_str="";
}
A(const char *str): m_str(str) {}
A(string str): m_str(str) {}
friend class B;
friend void B::put(const A&);
private:
string m_str;
};
void B::put(const A& a)
{
cout<<a.m_str<<endl;
}
int main()
{
A a="friend";
B b;
b.put(a);
return 0;
}
------解决方案--------------------
如果放在A类的上面的话,因为该函数要输出A类的数据,而此时还不知到A类的具体信息,所以系统会报错。