【问题标题】:No suitable constructor exists to convert from "const char[7]" to "TopicA"不存在将“const char[7]”转换为“TopicA”的合适构造函数
【发布时间】:2013-02-05 08:30:42
【问题描述】:

我有一个模板化的 SortedLinkedList 类,它按主题 A 对象的字符串字段中包含的值对其进行排序。

这里是主题 A:

struct TopicA
{
string sValue;
double dValue;
int iValue; 

TopicA();
TopicA( const string & arg );

bool operator> ( const TopicA & rhs ) const;
bool operator< ( const TopicA & rhs ) const;
bool operator== ( const TopicA & rhs ) const;
bool operator!= ( const TopicA & rhs ) const;
};

我想在列表中找到存储其字符串字段中带有"tulgey" 的TopicA 对象的位置,所以我调用AList.getPosition( "tulgey" ); 这是getPosition() 标头:

template <class ItemType>
int SortedLinkedList<ItemType>::getPosition( const ItemType& anEntry ) const

但是当我尝试调用 getPosition() 时,编译器在标题中给出了错误。为什么?难道我没有从stringTopicA 的转换构造函数吗?

如果有什么不同,这里是TopicA( const string &amp; arg )的定义:

TopicA::TopicA( const string & arg ) : sValue( arg ), dValue( 0 ), iValue( 0 )
{
}

【问题讨论】:

    标签: c++ templates constructor


    【解决方案1】:

    您可能正在调用两个隐式转换,从const char[7]std::string,以及从std::stringTopicA。但是您只允许进行一次隐式转换。您可以通过更明确的方式解决问题:

    AList.getPosition( std::string("tulgey") ); // 1 conversion
    AList.getPosition( TopicA("tulgey") );      // 1 conversion
    

    或者,您可以给TopicA 一个构造函数,采用const char*

    TopicA( const char * arg ) : sValue( arg ), dValue( 0 ), iValue( 0 ) {}
    

    【讨论】:

      【解决方案2】:

      这些都行

      AList.getPosition( TopicA("tulgey") ); 
      
      AList.getPosition( TopicA("tulgey") ); 
      
      std::string query = "tulgey";
      AList.getPosition( query  ); 
      

      您也可以定义另一个转换构造函数

      TopicA( const char* arg );
      

      现在一切如你所愿

      AList.getPosition( "tulgey" );
      

      问题是你需要2个隐式转换标准只允许1个。请记住,字符串文字在C++ 中表示为char 数组,而不是string

      1. char*/char[] -> std::string
      2. std::string -> TopicA

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-16
        • 2014-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多