重载 + 运算符
class Demo{
public:
int x,y;
public:
Demo(int j,k):x(j),y(k){}
Demo operator+(const Demo& other)
{
return Demo(x+other.x,y+other.y);
}
};
int main()
{
Demo d1(1,2);
Demo d2(3,4);
Demo d3=d1+d2;
}
d3(4,6)
重载 *运算符
class Demo{
public:
int x,y;
public:
Demo(int j,k):x(j),y(k){}
Demo operator*(const Demo& other)
{
return Demo(x+other.x,y+other.y);
}
};
int main()
{
Demo d1(1,2);
Demo d2(3,4);
Demo d3=d1*d2;
}
d3(3,6);
重载 << 运算符
#include <iostream>
class Demo{
public:
int x,y;
public:
Demo(int j,k):x(j),y(k){}
};
std::ostream& operator<< (std::ostream& stream,const Demo& demo)
{
stream << demo.x << "," << demo.y << std::endl;
return stream;
}
int main()
{
Demo d1(1,2);
Demo d2(3,4);
Demo d3=d1*d2;
std::cout<<d3<<std::endl;
}
3,8
重载 运算符
class Demo
{
public:
char* buffer;
unsigned int size;
Demo(const char* str)
{
size = strlen(str);
buffer = new char[size + 1];
memcpy(buffer, str, size);
buffer[size] = 0;
}
~Demo()
{
delete[] buffer;
}
char& operator[](unsigned int index)
{
return buffer[index];
}
};
int main()
{
Demo d("c++demo");
d[0] = 'a';
}