結構體內的一些操作
阿新 • • 發佈:2020-07-26
結構體內的一些操作
過載
#include <bits/stdc++.h> using namespace std; struct test { int a, b; friend bool operator < (const test &x, const test &y) { return x.a < x.b; } } x, y; int main() { cin >> x.a >> x.b; if(x < y) cout << 1; else cout << 0; return 0; }
加&:更快。相當於呼叫地址進行操作。如果不加&的話會非常慢,相當於把要操作的東西先複製了一遍。
加\(const\):保證要操作的東西不被改變。可以更快一點點。
加\(friend\):結構體中過載,後面如果有兩個引數,必須加\(friend\)。如果在結構體外過載就不用加了。
返回型別:上面的就是返回的\(bool\)型別,因為是過載小於號,別的該返回啥返回啥。
建構函式
#include <bits/stdc++.h> using namespace std; struct test { int a, b; char *ch[2]; test(int c = 0, int d = 0) : a(c), b(d) { ch[0] = ch[1] = NULL; } }; int main() { test x(1, 3), y; cout << x.a << " " << x.b << "\n"; cout << y.a << " " << y.b << "\n"; return 0; }
更簡單的初始化,注意要賦值的東西對應好了就行。如果沒有賦初值直接就是0。
保護(隱藏)
#include <bits/stdc++.h>
using namespace std;
struct Stack {
protected:
int a;
public:
void make() {
cout << ++a;
}
} cj;
int main() {
cj.make();
// cj.a++;
return 0;
}
我們平常寫的結構體內的所有東西都是在\(public\)中搞的,\(protected\)裡搞的東西只能在這個結構體裡用到,上面程式碼被註釋的是錯誤寫法,會報錯: