gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:04 24 4
gpt4 key购买 nike

我有一个模板化的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com