Jam*_*old 1 c++ templates constructor
我有一个模板化的 SortedLinkedList 类,它按主题 A 对象的字符串字段中包含的值对主题 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;
};
Run Code Online (Sandbox Code Playgroud)
我想找到列表中"tulgey"存储字符串字段中的 TopicA 对象的位置,所以我调用AList.getPosition( "tulgey" );Here is the getPosition()header:
template <class ItemType>
int SortedLinkedList<ItemType>::getPosition( const ItemType& anEntry ) const
Run Code Online (Sandbox Code Playgroud)
但是当我尝试调用getPosition()编译器时,标题中出现错误。为什么?我没有从stringto转换构造函数吗TopicA?
如果有什么区别的话,这里是 的定义TopicA( const string & arg ):
TopicA::TopicA( const string & arg ) : sValue( arg ), dValue( 0 ), iValue( 0 )
{
}
Run Code Online (Sandbox Code Playgroud)
您可能正在调用两个隐式转换: from const char[7]tostd::string和 from std::stringto TopicA。但只允许进行一次隐式转换。您可以通过更明确地解决问题:
AList.getPosition( std::string("tulgey") ); // 1 conversion
AList.getPosition( TopicA("tulgey") ); // 1 conversion
Run Code Online (Sandbox Code Playgroud)
或者,您可以给TopicA构造函数采用const char*:
TopicA( const char * arg ) : sValue( arg ), dValue( 0 ), iValue( 0 ) {}
Run Code Online (Sandbox Code Playgroud)