operator<<友元类的类外定义

来源:互联网 发布:看不到etc linux 编辑:程序博客网 时间:2024/06/14 21:28
#include<iostream>
#include<iomanip>
using namespace std;
class Rectangle
{
public:
Rectangle(){}
Rectangle(float l1,float r1,float l2,float r2):left1(l1),right1(r1),left2(l2),right2(r2){}
void input(){cin>>left1>>right1>>left2>>right2;}
Rectangle operator+(Rectangle &);
friend ostream&operator<<(ostream& x,Rectangle& p)
{

cout<<((p.right2 -p.right1)*(p.left2-p.left1));
cout<<setiosflags(ios::fixed)<<setprecision(2);
cout<<endl;
return x;
}
private:
float left1;
float right1;
float left2;
float right2;
};
Rectangle Rectangle::operator+(Rectangle &p2)
{
Rectangle p;
p.left1=left1+p2.left1;
p.right1=right1+p2.right1;
p.left2=left2+p2.left2;
p.right2=right2+p2.right2;
return p;
}


int main()
{
    Rectangle p1(1,1,6,3),p2,p3;
    p2.input();
    p3=p1+p2;
    cout<<p3;
    return 0;

}

此中friend ostream&operator<<(ostream& x,Rectangle& p),只可在类内定义,在类外会出现

In file included from /usr/include/c++/4.4/ios:39,                 from /usr/include/c++/4.4/ostream:40,                 from /usr/include/c++/4.4/iostream:40,                 from Main.cc:2:/usr/include/c++/4.4/bits/ios_base.h: In copy constructor 'std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)':/usr/include/c++/4.4/bits/ios_base.h:790: error: 'std::ios_base::ios_base(const std::ios_base&)' is private/usr/include/c++/4.4/iosfwd:47: error: within this context/usr/include/c++/4.4/iosfwd: In copy constructor 'std::basic_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)':/usr/include/c++/4.4/iosfwd:56: note: synthesized method 'std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)' first required here Main.cc: In function 'std::ostream operator<<(std::ostream&, Rectangle&)':Main.cc:39: note: synthesized method 'std::basic_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)' first required here 

0 0
原创粉丝点击