zoukankan      html  css  js  c++  java
  • 初遇构造函数

    在翻刘汝佳的紫书的时候看见一种奇怪的结构体写法:

    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

  • 相关阅读:
    ACM-生化武器
    ACM-Antiprime数
    ACM-寻宝
    ACM-小偷的背包
    ACM-吴奶奶买鱼
    ACM-挑战题之排列生成
    ACM-数细胞
    ACM-售货员难题
    学习《linux》课程
    MATLAB 求圆形面积
  • 原文地址:https://www.cnblogs.com/antiquality/p/8511311.html
Copyright © 2011-2022 走看看