c++ - 不存在合适的构造函数来从 "const char[7]"转换为 "TopicA"

标签 c++ templates constructor

我有一个模板化的 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() 时,编译器在标题中给出了错误。为什么?难道我没有从 stringTopicA 的转换构造函数吗?

如果它有任何不同,这里是 TopicA( const string & arg ) 的定义:

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

最佳答案

您可能正在调用两个隐式转换,从 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 ) {}

关于c++ - 不存在合适的构造函数来从 "const char[7]"转换为 "TopicA",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14703086/

相关文章:

c++ - 通过 boost::beast 设计不同订阅率的多个订阅

c++ - 错误 : too many template-parameter-lists

c++ - 访问基类型数组成员(Int-to-Type 习语)

c++ - 这行得通吗? C++ 多重继承和构造函数链接

c++ - QT 不清楚的移位运算符行为

C++ 将一个整数转换为其字形式

c++ - 从 Objective C 类调用 Objective C++ 方法

c++ - OpenCV 模板化代码在派生类中产生编译错误

javascript - 获取新对象的对象变量名

javascript - new Thing(param) 和 new(Thing(param)) 有什么区别?