Example analysis of C++ structure usage
- 2020-04-02 02:58:24
- OfStack
This article illustrates the use of C++ constructs. Share with you for your reference. Specific analysis is as follows:
C++ structs provide more functionality than C structs, such as default constructors, copy constructors, and operator overloads, which make it easy for struct objects to pass values.
For example, I define a simple structure and use it as a vector element type. To use it, I need to implement the above three functions, otherwise I have to use Pointers.
#include <iostream>
#include <vector>
using namespace std;
struct ST
{
int a;
int b;
ST() //Default constructor & NBSP; < br / >
{
a = 0;
b = 0;
}
void set(ST* s1,ST* s2)//Assignment function & PI; < br / >
{
s1->a = s2->a;
s1->b = s2->b;
}
ST& operator=(const ST& s)//Overloaded operator & NBSP; < br / >
{
set(this,(ST*)&s)
}
ST(const ST& s)//Copy constructor & NBSP; < br / >
{
*this = s;
}
};
int main()
{
ST a ; // call Default constructor & NBSP; < br / >
vector<ST> v;
v.push_back(a); // call Copy constructor & NBSP; < br / >
ST s = v.at(0); //Call = function & NBSP; < br / >
cout << s.a <<" " << s.b << endl;
cin >> a.a;
return 0;
}
Hope that the article described in the C++ programming to help you.