正如话题所述。有没有可能做到这一点?我能够在超载“+”运算符中实现这一点,但是,我无法通过'< <'运算符来实现。C++ <<不带朋友功能的操作符重载
这是与朋友的功能对我的作品的代码示例:
class Punkt2D
{
int x,y;
public:
Punkt2D(int wartoscX, int wartoscY) : x(wartoscX), y(wartoscY) {}
friend ostream& operator<<(ostream& out, Punkt2D& punkt);
};
ostream& operator<<(ostream& out, Punkt2D& punkt)
{
out << "(" << punkt.x << ", " << punkt.y << ")" << endl;
return out;
}
int main()
{
Punkt2D p1(10,15);
cout << p1 << endl;
return 0;
}
我尝试这个代码在“+”不结交功能。其他运营商也有可能吗?也许这是一个愚蠢的问题,但我很新的C++,找不到的话题:(
class Vector
{
public:
double dx, dy;
Vector() {dx=0; dy=0;}
Vector(double x, double y)
{
cout << "Podaj x " << endl;
cin >>x;
cout << "Podaj y " << endl;
cin >> y;
dx = x; dy = y;
}
Vector operator+ (Vector v);
};
Vector Vector::operator+ (Vector v)
{
Vector tmpVector;
tmpVector.dx = dx +v.dx;
tmpVector.dy = dy+ v.dy;
return tmpVector;
}
int main()
{
double d,e;
Vector a(d,e);
Vector b(d,e);
Vector c;
c = a +b;
cout<<endl << c.dy << " " << c.dx;
return 0;
}
好吧,我有点困惑,因为答案似乎是矛盾的。 如果该类的所有成员都是公共的,那么该代码行看起来会不会使该函数变得友好? 我只关注ostream元素,即函数的声明和定义。 – Andy
由于声明不是类的成员(例如在头文件中),所以在类声明之后将声明形式'std :: ostream&operator <<(std :: ostream&out,const Punkt2D&punkt)'。运算符<<()的定义(即实现)(它需要在某处,但不需要在头中,除非被内联),则需要避免访问“私有”或“受保护的成员全班同学 – Peter
谢谢彼得:) – Andy