當前位置:
首頁 >
初遇构造函数
發布時間:2025/7/14
35
豆豆
在翻劉汝佳的紫書的時候看見一種奇怪的結構體寫法:
struct Edge {int from, to, dist;Edge(int u, int v, int d):from(u), to(v), dist(d) {} };這里有兩個奇怪的東西
1.?Edge(int u, int v, int d)?結構體里面套了一個什么玩意?
2.?from(u), to(v), dist(d)?這是什么打法?
問了下余翱,第一個是構造函數,可以在main里面調用從而快速賦值。
例如
... int main() {...vector<Edge> edges;edges.push_back(Edge(from, to, dist));...return 0; }第二個是元素賦值的另一種方式。
#include<bits/stdc++.h> using namespace std; int a(5),b; int main() {cout << a << "#" << b << endl;return 0; }——輸出是 5#0
?
妙啊妙啊,這樣子就可以賦值結構體了。不然point這些的還要提出來再操作……
但是這樣子是會CE的
#include<bits/stdc++.h> using namespace std; struct p{int x; p(int x):x(x) {}; }f[1003]; int main() {return 0; }實際上是要這樣
#include<bits/stdc++.h> using namespace std; struct p{int x; p() {};p(int x):x(x) {}; }f[1003]; int main() {return 0; }因為在int main之前有申請f[],那么前一個版本并沒有對其賦默認值,所以沒法過編。
至于之后的那一行,是說明p這個結構體初始不進行任何操作。
?
找到的一些參考資料:
1.淺談C++中的幾種構造函數
2.構造函數_BaiduBaike
轉載于:https://www.cnblogs.com/antiquality/p/8511311.html
總結
- 上一篇: PHP中调用SVN命令更新网站方法(解决
- 下一篇: bootsrap+jquery+组件项目