为 C 风格字符串创建 std::initializer_list 构造函数
Creating std::initializer_list Constructor for c-style strings
我正在为大学创建一个 Graph 程序,并为该图创建了一个 std::initializer_list
构造函数,如下所示:
Graph(std::initializer_list< std::string >& _vertices_){
// ... initialising my map of vertices with their names
}
但是,当我尝试在我的主程序中初始化图形时:
int main(){
Graph g = { "A", "B", "C", "D", "F", "G" }; //Error: Does not compile
g.connectEdge( "A", "B" ).setWeight( 2 );
// ... connecting other edges
g.set_path_algorithm( Graph::DJIKSTRA );
int cost = g.find_shortest< Graph::COST >("A", "G");
//int hops = g.find_shortest< Graph::HOPS >("A", "G");
std::cout << "The shortest path between A and G is: " << cost ;
return 0;
}
我得到:
test_djikstra.cpp: In function 'int main()':
test_djikstra.cpp:36:46: error: could not convert '{"A", "B", "C", "D", "F", "G"}' from '<brace-enclosed initializer list>' to 'Graph'
Graph g = { "A", "B", "C", "D", "F", "G" };
^
现在,当我创建一个采用 std::string
并传递 c 风格字符串
(const char []
) 的构造函数时,函数将其转换为 std::string
自动调用。
为什么这不会将每个 const char []
参数转换为 std::string
?
问题是什么,可能的解决方案是什么?
编辑:所以我正在创建对临时对象的引用。微妙的!
谢谢@rafix07
.
这个
{ "A", "B", "C", "D", "F", "G" }
创建初始化列表对象。它是临时实例。临时对象不能绑定到 左值引用。
解决方案:
[1] 使 const 引用
Graph(const std::initializer_list< std::string >& _vertices_)
[2] 仅丢弃引用
Graph(std::initializer_list< std::string > _vertices_)
Initializer list 是轻量级对象(可以被视为对:指向数据的指针+长度),因此复制它并不昂贵。
我正在为大学创建一个 Graph 程序,并为该图创建了一个 std::initializer_list
构造函数,如下所示:
Graph(std::initializer_list< std::string >& _vertices_){
// ... initialising my map of vertices with their names
}
但是,当我尝试在我的主程序中初始化图形时:
int main(){
Graph g = { "A", "B", "C", "D", "F", "G" }; //Error: Does not compile
g.connectEdge( "A", "B" ).setWeight( 2 );
// ... connecting other edges
g.set_path_algorithm( Graph::DJIKSTRA );
int cost = g.find_shortest< Graph::COST >("A", "G");
//int hops = g.find_shortest< Graph::HOPS >("A", "G");
std::cout << "The shortest path between A and G is: " << cost ;
return 0;
}
我得到:
test_djikstra.cpp: In function 'int main()':
test_djikstra.cpp:36:46: error: could not convert '{"A", "B", "C", "D", "F", "G"}' from '<brace-enclosed initializer list>' to 'Graph'
Graph g = { "A", "B", "C", "D", "F", "G" };
^
现在,当我创建一个采用 std::string
并传递 c 风格字符串
(const char []
) 的构造函数时,函数将其转换为 std::string
自动调用。
为什么这不会将每个 const char []
参数转换为 std::string
?
问题是什么,可能的解决方案是什么?
编辑:所以我正在创建对临时对象的引用。微妙的!
谢谢@rafix07
.
这个
{ "A", "B", "C", "D", "F", "G" }
创建初始化列表对象。它是临时实例。临时对象不能绑定到 左值引用。
解决方案:
[1] 使 const 引用
Graph(const std::initializer_list< std::string >& _vertices_)
[2] 仅丢弃引用
Graph(std::initializer_list< std::string > _vertices_)
Initializer list 是轻量级对象(可以被视为对:指向数据的指针+长度),因此复制它并不昂贵。