1-逻辑运算符.cpp
#include <iostream>
using namespace std;
int f1()
{
cout << "this is f1" << endl;
return 0;
}
int f2()
{
cout << "this is f2" << endl;
return 1;
}
class Complex
{
private:
int a;
int b;
public:
Complex(int a, int b)
{
this->a = a;
this->b = b;
}
Complex operator+(const Complex &c)
{
cout << "operator+" << endl;
Complex t(0, 0);
t.a = this->a + c.a;
t.b = this->b + c.b;
return t;
}
bool operator&&(const Complex &c)
{
return (this->a && c.a) && (this->b && c.b);
}
};
int main()
{
if (f1() && f2()) //短路原则:如果f1()不成立,则不会执行f2()
{
cout << "helloworld" << endl;
}
Complex c1(1, 1);
Complex c2(2, 2);
Complex c3(0, 0);
if (c1 && c2)
{
cout << "成立" << endl;
}
if (c1 && c3)
{
cout << "成立" << endl;
}
//c3.operator&&(c1 + c2) c3.operator&&(c1.operator+(c2))
if (c3 && (c1 + c2)) //重载逻辑&&违背了短路原则 所以不要重载逻辑&& ||
{
}
return 0;
}
2-数组类.cpp
#include <iostream>
using namespace std;
class Array
{
private:
int *data;
int size;
public:
Array(int s)
{
size = s;
data = new int[size];
}
int &operator[](int Index)
{
return data[Index];
}
bool operator==(const Array &a)
{
/*if (this->size != a.size)
{
return false;
}
for (int i = 0; i < size; i++)
{
if (this->data[i] != a.data[i])
{
return false;
}
}
return true;*/
return (this->data == a.data && this->size == a.size);
}
Array &operator=(const Array &a) //赋值运算符只能重载成成员函数
{
if (*this == a)
{
return *this;
}
this->size = a.size;
delete this->data;
this->data = new int[size];
for (int i = 0; i < size; i++)
{
this->data[i] = a.data[i];
}
}
~Array()
{
if (data != NULL)
{
delete[] data;
}
}
};
int main()
{
Array a1(10); //创建数组对象
//a1[0] = 100;
//data[0] = 100;
for (int i = 0; i < 10; i++)
{
a1[i] = i + 10; //a1.operator[](i) = i + 10
}
for (int i = 0; i < 10; i++)
{
cout << a1[i] << endl;
}
Array a2(5);
//a1 = a2; //所有类都默认重载了=运算符,但是只是简单的赋值(浅拷贝)
a1 = a1;
for (int i = 0; i < 10; i++)
{
cout << a1[i] << endl;
}
return 0;
}
3-智能指针.cpp
#include <iostream>
#include <memory>
using namespace std;
class Test
{
public:
Test()
{
cout << "Test构造函数" << endl;
}
void print()
{
cout << "xxx" << endl;
}
~Test()
{
cout << "Test析构函数" << endl;
}
};
void f1()
{
Test *pt = new Test; //内存泄漏
}
void f2()
{
auto_ptr<Test> my_memory(new Test);
my_memory->print(); //my_mempry.operator->(print())
}
int main()
{
//f1();
f2();
return 0;
}
test.cpp
#include <iostream>
using namespace std;
int main()
{
int a, b;
//(a + b) = 1; //+不能作为左值使用 重载+运算符不能返回引用
(a = b) = 1;
return 0;
}