友链
关注微信公众号回复关键字【资料】获取各种学习资料
在C++中,struct与class最主要的区别是默认访问权限和继承方式不同,在其他方面的差异很小。
在class中可以实现的各种重载运算符操作在struct中一样可以,而且可以在struct中定义含默认形参的构造函数
#include<iostream> using namespace std; struct Point { int x, y; Point(int x = 0, int y = 0) : x(x), y(y) {} //列表初始化 }; Point operator + (const Point& A, const Point& B) { return Point(A.x + B.x, A.y + B.y); } ostream& operator << (ostream& out, const Point& p) { out << "(" << p.x << "," << p.y << ")"; return out; } int main() { Point a, b(1, 2); a.x = 3; cout << a + b << "\n"; return 0; }上面的Point结构体重载了“+”运算符和流输出方式
可以通过定义一个模板来提高函数的复用性,
template<typename T> T sum(T* begin, T* end) { T *p = begin; T ans = 0; for(T *p = begin; p != end; p++) ans = ans + *p; return ans; }这样一来,sum函数就可以计算各种数据类型的数组的和了
#include<iostream> using namespace std; struct Point { int x, y; Point(int x = 0, int y = 0) : x(x), y(y) {} }; Point operator + (const Point& A, const Point& B) { return Point(A.x + B.x, A.y + B.y); } ostream& operator << (ostream& out, const Point& p) { out << "(" << p.x << "," << p.y << ")"; return out; } template<typename T> T sum(T* begin, T* end) { T *p = begin; T ans = 0; for(T *p = begin; p != end; p++) ans = ans + *p; return ans; } int main() { double a[] = {1.1, 2.2, 3.3, 4.4}; cout << sum(a, a + 4) << "\n"; Point b[] = {Point(1, 2), Point(3, 4), Point(5, 6), Point(7 ,8)}; cout << sum(b, b + 4) << "\n"; return 0; }上面的代码中之所以写成ans = ans + p而不写成ans += p,是因为Point结构体中并没有定义+=运算符。
结构体和类自身也是可以带模板的,上面的Point结构体中,它的成员是int型的,如果需要double或者其他类型的,就需要再重新声明一个结构体,这时候如果有一个模板,就会非常方便。
#include<iostream> using namespace std; template <typename T> struct Point { T x, y; Point(T x = 0, T y = 0) : x(x),y(y) {} }; template <typename T> Point<T> operator + (const Point<T>& A, const Point<T>& B) { return Point<T>(A.x + B.x, A.y + B.y); } template <typename T> ostream& operator << (ostream& out, const Point<T>& p) { out << "(" << p.x << "," << p.y << ")"; return out; } int main() { Point<int> a(1, 2), b(3, 4); Point<double> c(1.1, 2.2), d(3.3, 4.4); cout<< a + b << " " << c + d << "\n"; return 0; }