【问题标题】:(std::__cxx11::string) [with T = std::__cxx11::basic_string<char>; std::__cxx11::string = std::__cxx11::basic_string<char>] cannot be overloaded(std::__cxx11::string) [with T = std::__cxx11::basic_string<char>; std :: __ cxx11 :: string = std :: __ cxx11 :: basic_string <char>]不能超载
【发布时间】:2018-03-11 08:57:24
【问题描述】:

C++ 在模板中显示构造函数重载错误

(std::__cxx11::string) [with T = std::__cxx11::basic_string<char>; std::__cxx11::string = std::__cxx11::basic_string<char>]cannot be overloaded

我试图在这里重载一个模板类构造函数。 扩展错误:

In file included from main.cpp:2:0:
dlist.h: In instantiation of class Sinwan::DList::DoublyLinkList<std::__cxx11::basic_string<char> >:
main.cpp:5:45:   required from here
dlist.h:62:13: error:Sinwan::DList::DoublyLinkList<T>::DoublyLinkList(std::__cxx11::string) [with T = std::__cxx11::basic_string<char>; std::__cxx11::string = std::__cxx11::basic_string<char>] cannot be overloaded
             DoublyLinkList(std::string dummyData_)
             ^
dlist.h:52:13: error: with Sinwan::DList::DoublyLinkList<T>::DoublyLinkList(T) [with T = std::__cxx11::basic_string<char>]
             DoublyLinkList(T dummyData_)

我的 .h 文件中的代码:

DoublyLinkList(T dummyData_)
{
    node = new Node;//dummy node
    node->_next=NULL;
    node->_prev=NULL;
    node->_data=dummyData_;
    head=node;
    tail=node;
    _iteratorObj=begin();
}
DoublyLinkList(std::string dummyData_)
{
    node = new Node;//dummy node
    node->_next=NULL;
    node->_prev=NULL;
    node->_data=dummyData_;
    head=node;
    tail=node;
    _iteratorObj=begin();
} 

Main.cpp:

#include&lt;iostream&gt;

#include "dlist.h"

int main()

{

Sinwan::DList::DoublyLinkList&lt;std::string&gt;::Iterator it;

Sinwan::DList::DoublyLinkList&lt;std::string&gt; listObj("0");

}

如果我将 std::string 更改为 int,它可以正常工作。谁能帮我指出prblm??

【问题讨论】:

  • 这不可能是完整的错误。请复制粘贴完整且完整的错误输出,包括可能的信息说明。然后请在Minimal, Complete, and Verifiable Example 中标出错误所在的位置,例如用评论。

标签: c++ string c++11 stl


【解决方案1】:

我们仍然没有Minimal, Complete, and Verifiable Example,但至少可以猜测这个问题。

假设T 是一个类模板参数,那么如果您有DoublyLinkList&lt;std::string&gt;,那么T 类型将是std::string,并且您将有两个 构造函数采用std::string作为论据。你不能这样,如果你重载一个函数(构造函数或其他)它必须有不同的签名。

您可能不应该让构造函数采用显式 std::string 参数。

【讨论】:

  • 好的,那么当模板为字符串类型时,我该怎么做才能用“0”(字符串0)初始化节点->数据,当模板类型为时,节点->数据为0(int 0)诠释
  • @SinwanMohammed 这将通过将正确的参数传递给构造函数来自动发生。如果您有 std::string 对象的列表,那么您将传递 std::string 参数。如果您有一个 int 值列表,那么您将传递 int 值。
  • 谢谢老兄,这很有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2015-04-28
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 2021-09-16
  • 2021-07-19
相关资源
最近更新 更多