#include <iostream>
#include <string>
using namespace std;
class Point
{
public:
// Declare prefix and postfix increment operators.
Point &operator++(); // Prefix increment operator.
Point operator++(int); // Postfix increment operator.
// Declare prefix and postfix decrement operators.
Point &operator--(); // Prefix decrement operator.
Point operator--(int); // Postfix decrement operator.
// Define default constructor.
Point()
{
cout << "constructor" << endl;
_x = _y = 0;
}
// 如果显示定义拷贝构造,对象数据成员之间的赋值都必须指明
Point(const Point &p)
{
this->_x = p.x(); // const对象只能调用const成员函数
this->_y = p.y();
cout << "Point(const Point &p)" << endl;
}
Point &operator=(const Point &p)
{
this->_x = p.x(); // const对象只能调用const成员函数
this->_y = p.y();
cout << "Point &operator=" << endl;
return *this;
}
// Define accessor functions.
int x() const { return _x; }
int y() const { return _y; }
private:
int _x, _y;
};
// Define prefix increment operator.
Point &Point::operator++()
{
_x++;
_y++;
return *this;
}
// Define postfix increment operator.
Point Point::operator++(int)
{
Point temp = *this;
++*this;
return temp;
}
// Define prefix decrement operator.
Point &Point::operator--()
{
_x--;
_y--;
return *this;
}
// Define postfix decrement operator.
Point Point::operator--(int)
{
Point temp = *this;
--*this;
return temp;
}
int main()
{
Point s, b;
cout << s.x() << " " << s.y() << endl;
cout << b.x() << " " << b.y() << endl;
b = s++;
cout << s.x() << " " << s.y() << endl;
cout << b.x() << " " << b.y() << endl;
b = ++s;
cout << s.x() << " " << s.y() << endl;
cout << b.x() << " " << b.y() << endl;
b = s--;
cout << s.x() << " " << s.y() << endl;
cout << b.x() << " " << b.y() << endl;
b = --s;
cout << s.x() << " " << s.y() << endl;
cout << b.x() << " " << b.y() << endl;
cout << "-------------a---------------" << endl;
Point a; // 定义对象 会调用构造
cout << a.x() << " " << a.y() << endl;
cout << "--------------c--------------" << endl;
Point *c = new Point(); // 定义指针 并同时new 会调用构造
cout << c->x() << " " << c->y() << endl;
cout << "--------------f--------------" << endl;
Point *f = &a; // 此处不会调用拷贝构造 这是指针方式 如果用对象的方式会调用
cout << f->x() << " " << f->y() << endl;
cout << "--------------k--------------" << endl;
Point k = a; // 此处会调用拷贝构造 对象的方式
cout << k.x() << " " << k.y() << endl;
cout << "--------------d--------------" << endl;
Point *d = nullptr; // 单纯的指针 并不会调用构造
cout << d << endl;
d = &a; // 此处不会调用拷贝赋值 指针方式
cout << &a << " " << d << endl;
cout << d->x() << " " << d->y() << endl;
d = new Point(); // 调用构造,但不会调用赋值构造
cout << d << endl;
cout << d->x() << " " << d->y() << endl;
cout << "--------------kkkkk--------------" << endl;
f = d; // 改变指向
cout << f << endl;
cout << "--------------h--------------" << endl;
Point h; // 普通构造
h = a; // 此处会调用拷贝赋值 对象方式
cout << h.x() << " " << h.y() << endl;
}
c++ 构造 拷贝构造 拷贝赋值 何时触发
于 2023-09-16 13:32:05 首次发布