gpt4 book ai didi

c++ - ":"Struct 构造函数中的冒号

转载 作者:行者123 更新时间:2023-11-28 05:25:21 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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

(13 个回答)


5年前关闭。




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

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 的构造函数范围。在构造函数中,:开始 成员初始化列表 ,它初始化成员值并调用成员构造函数。以下括号是实际的构造函数主体,在本例中为空。

Constructors and member initializer lists更多细节。

关于c++ - ":"Struct 构造函数中的冒号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40666868/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com