and just return *this. ... // Deallocate, allocate new space, copy values... return *this; } Or, you can simplify this a bit by doing: MyClass& MyClass::operator=(const MyClass &rhs) { // Only do assignment if
分类: C/C++ 操作符重载有两种方式,一是以成员函数方式重载,另一种是全局函数。先看例子#include <iostream>#include <string>using namespace std;/* defualt operator= differ from my own one.* assign 0 or 1 to TEST_EQ, look the diference*/...
由于ofstream和cout一样,也是ostream的一种,所以我们也可以直接不用再写新代码就可以将对象写入文件(输出变量的值到文件): #include <iostream> #include <fstream> #include <string> class Student { friend std::ostream& operator<<(std::ostream& os, const Student& stu); public: std::string m_id;/...
const Point Point::operator++(int) { Point point(this->m_x, this->m_y); this->m_x++; this->m_y++; return point; } ostream &operator<<(ostream &cout, const Point &point) { return cout << "(" << point.m_x << ", " << point.m_y << ")"; } 1. 2. 3. 4. 5. ...
getCents() << endl; cout << c4.getCents() << endl; return 0; } 和友元函数相比,成员函数的运算符重载只有一个参数。c1看起来变成了前缀。而这里隐藏了*this,即c1.operator+(2)实际上是operator(&c1, 2)。 使用范围 赋值=,偏且[],调用函数(),成员选择->,这几个操作符必须要作为成员函数。
InsertionOperator(<<)forstdout:<<本来是位左移运算符,但是在C++的标准库iostream中被改头换面,其左侧的运算元(operand)被指定为cout(console output device),右侧运算元是一个内建型别的objects。我们可以利用它很方便的对cout连续输出各种内建型别的数据或信息(也是一种objects),不必像C程序那样需要识别不同类型...
// operator_overloading.cpp // compile with: /EHsc #include <iostream> using namespace std; struct Complex { Complex( double r, double i ) : re(r), im(i) {} Complex operator+( Complex &other ); void Display( ) { cout << re << ", " << im << endl; } private: double re...
// constructor to initialize count to 5 Count() : value(5) {} // overload ++ when used as prefix void operator ++ () { ++value; } void display() { cout << "Count: " << value << endl; } }; int main() { Count count1; // call the "void operator ++ ()" function ++cou...
31operator--(Integer&a); 32//Postfix: 33friendconstInteger 34operator--(Integer&a,int); 35}; 36 37//Global operators: 38constInteger&operator+(constInteger&a) { 39cout<<"+Integer\n"; 40returna;//Unary + has no effect 41}
The left operand is the std::cout object, and the right operand is your Point class object. std::cout is actually an object of type std::ostream. Therefore, our overloaded function will look like this: // std::ostream is the type for object std::cout friend std::ostream& operator<<...