我有一个模板化的 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()
header :
template <class ItemType>
int SortedLinkedList<ItemType>::getPosition( const ItemType& anEntry ) const
但是当我尝试调用 getPosition()
时,编译器在标题中给出了错误。为什么?难道我没有从 string
到 TopicA
的转换构造函数吗?
如果它有任何不同,这里是 TopicA( const string & arg )
的定义:
TopicA::TopicA( const string & arg ) : sValue( arg ), dValue( 0 ), iValue( 0 )
{
}
最佳答案
您可能正在调用两个隐式转换,从 const char[7]
到 std::string
,以及从 std::string
到 TopicA
。但是您只允许进行一次隐式转换。您可以通过更明确的方式解决问题:
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 ) {}
关于c++ - 不存在合适的构造函数来从 "const char[7]"转换为 "TopicA",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14703086/