“:”结构构造函数中的冒号

时间:2016-11-17 23:25:59

标签: c++ struct constructor colon

我在结构构造函数中检查了一些关于Bitfields的主题,但我找不到关于这行代码的任何解释:

vertex(string s) : name(s) {}

在这段代码中:

struct vertex {
   typedef pair<int, vertex*> ve;
   vector<ve> adj; //cost of edge, destination vertex
   string name;
   vertex(string s) : name(s) {}
};

整个代码结构是关于实现我在本网站上看到的加权图:

#include <iostream>
#include <vector>
#include <map>
#include <string>

using namespace std;

struct vertex {
    typedef pair<int, vertex*> ve;
    vector<ve> adj; //cost of edge, destination vertex
    string name;
    vertex(string s) : name(s) {}
};

class graph
{
public:
    typedef map<string, vertex *> vmap;
    vmap work;
    void addvertex(const string&);
    void addedge(const string& from, const string& to, double cost);
};

void graph::addvertex(const string &name)
{
    vmap::iterator itr = work.find(name);
    if (itr == work.end())
    {
        vertex *v;
        v = new vertex(name);
        work[name] = v;
        return;
    }
    cout << "\nVertex already exists!";
}

void graph::addedge(const string& from, const string& to, double cost)
{
    vertex *f = (work.find(from)->second);
    vertex *t = (work.find(to)->second);
    pair<int, vertex *> edge = make_pair(cost, t);
    f->adj.push_back(edge);
}

这一点做了什么,目的是什么?

vertex(string s) : name(s) {}

2 个答案:

答案 0 :(得分:1)

vertex是结构名称,因此vertex(string s)是具有string参数的构造函数。在构造函数中,:开始成员初始化列表,它初始化成员值并调用成员构造函数。以下括号是实际的构造函数体,在本例中为空。

有关详细信息,请参阅Constructors and member initializer lists

答案 1 :(得分:0)

这似乎构造了一个顶点结构。 : name(s)语法将结构name字段设置为s

请参阅What is this weird colon-member (" : ") syntax in the constructor?

相关问题