1. 运算符重载怎么写
关键字是operator
重载运算符
除了预先定义的运算功能之处,用户还可以通过类或者结构中的设置operator声明来实现运算符的用户定义运算功能,用户定义的运算符的优先级总是高于预定义运算符实现的优先级。只有当没有适用的用户定义运算符实现存在时,才会考虑预定义的运算符实现。
重载运算符时一般使用operator关键字,对于一元和二元运算符,它们重载函数的方法如下表所示。
序号 运算符 运算符重载函数
1 op x operate op(x)
2 x op operate op(x)
3 x op y operate op(x,y)
2. c++中<<运算符重载怎么写啊
class MyClass{ int member1; string member2; friend ostream& operator<<(ostream& out, const MyClass& myclass){ out< 也可以不重载为友元,而改用成员函数获取成员变量的值。我们平常写cout<。 class MyClass{ int member1; string member2; friend ostream& operator<<(ostream& out, const MyClass& myclass){ out<<member1<<member2; return out; } } 大概就是这么写。也可以不重载为友元,而改用成员函数获取成员变量的值。 我们平常写cout<<a<<"sdfghj"<<endl;为什么能成立, 就是因为<<;在iostream 里进行了重载。 而 cout 是在 iostream 里定义的,ostream类的对象。 在重载<<;时,返回值类型是ostream&, 第一个参数也是ostream& 。也就是说,表达式cout<<a的返回值仍是 cout。因此cout<<a<<"sdfghj"才能成立。 10 public: 11 S(int i = 0, int j = 0):n(n), m(m){} 12 friend S operator+(S& s, C& c) 13 { 14 c.i = s.n; 15 c.j = s.m; 16 } S& operator =(S&a) { *this.i=a.i; *this.j=a.j; return *this; } 重载<<;运算符用来输出对象的内容。 class POINT { private : int x; int y; public : POINT(int dx = 0, int dy = 0) { x = dx; y = dy; } ostream &operator<<(ostream &os, POINT const &pt) { os << "(" << pt.x << "," << pt.y << ")" << endl; return os; } ~POINT() {} }; //X++/Y //"++"为成员函数重载运算符,"/"为友元函数重载运算符,表达式又怎么写?? class A{public: A() : m_iSum(0) {} A(int iSum) : m_iSum(iSum) { } ~A(){}private: int m_iSum;public: A &operator ++(int) { this->m_iSum++; return *this; } friend A operator /(const A &a, const A &b);};A operator /(const A &a, const A &b){ A c; if (0 != b.m_iSum) c.m_iSum = a.m_iSum / b.m_iSum; return c;}//"++"为友元函数重载运算符,"/"为成员函数重载运算符,表达式怎么写?? class B{public: B() : m_iSum(0) { } B(int iSum) : m_iSum(iSum) { } ~B(){}private: int m_iSum;public: B &operator /(const B &a) { B c; if (0 != a.m_iSum) c.m_iSum = this->m_iSum / a.m_iSum; return c; } friend B &operator ++(B &a, int);};B &operator ++(B &a, int){ a.m_iSum ++; return a;}int main(){ A x(9); A y(5); A z; z = x++/y; B m(9); B n(5); B k; k = m++/n; int a=0;}//看代码,不明白再问。 A &operator ++(int) 为什么返回引用? 为了能够链式使用。如果直接void opertor ++(int)那么只能是x++,而不能x++/y,因为/两边必须为X。 friend A operator /(const A &a, const A&b); 为什么用引用?? 如果friend A operator /(const A a, const A b);也没问题,只不过参数传递的时候要调用一下构造函数重新生成一个对象,函数返回时调用析构函数撤销这个对象,有时间和空间的开销。而引用就是使用实参自己,尤其是对象作为参数的时候最好用引用。 #include 关于这部分,看以下两个帖子:第一个是运算符重载的一些介意规则,第二个能看到声明为友元的好处。3. c++中<<运算符重载怎么写啊
4. c++运算符重载,怎么写啊
5. 可以教教我 <<左移运算符重载怎么写么
6. 运算符重载
7. c++,如何利用运算符重载呢