“:”冒号在结构构造函数
问题描述:
我也查了一下位字段的一些话题结构构造函数,但我无法找到这行代码任何解释:在这个代码块“:”冒号在结构构造函数
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) {}
答
vertex
是结构名称,所以vertex(string s)
是一个带有string
参数的构造函数。在构造函数中,:
开始成员初始化列表,它初始化成员值并调用成员构造函数。下面的括号是实际的构造函数体,在这种情况下它是空的。
答
这似乎构造了一个顶点结构。 : name(s)
语法设置结构的name
字段等于s
。
参见What is this weird colon-member (" : ") syntax in the constructor?。