【问题标题】:no matching conversion for functional-style cast from 'int' to 'ItemType'从“int”到“ItemType”的函数式转换没有匹配的转换
【发布时间】:2020-06-06 03:21:43
【问题描述】:

我有一个家庭作业,我必须为链表编写一些方法,并使用教授的驱动程序进行测试。我一直遇到这个错误: no matching conversion for functional-style cast from 'int' to 'ItemType'

这是我的“节点”类 ItemType 的文件:

// ItemType.h. 

#include <fstream>
const int MAX_ITEMS = 5;
enum RelationType  {LESS, GREATER, EQUAL};

class ItemType{
public:
ItemType();
RelationType ComparedTo(ItemType) const;
void Print(std::ostream&) const;
void Initialize(int number);
private: int value;
};

还有ItemType.cpp

#include <fstream>
#include <iostream>
#include "ItemType.h"

ItemType::ItemType()
{
  value = 0;
}

RelationType ItemType::ComparedTo(ItemType otherItem) const 
{
  if (value < otherItem.value)
    return LESS;
  else if (value > otherItem.value)
    return GREATER;
  else return EQUAL;
}

void ItemType::Initialize(int number) 
{
  value = number;
}

void ItemType::Print(std::ostream& out) const 
// pre:  out has been opened.
// post: value has been sent to the stream out.
{
  out << value;
}

当我尝试使用教授驱动程序时,使用构造函数初始化 ItemType 类时出现错误。我像这样初始化它们:classList.putItem(ItemType(4)) 但我最终得到了上述错误,我不确定我错在哪里,这是我的驱动程序:

#include "unsorted.h"
using namespace std;

int main() {
    UnsortedType classList;


    classList.PutItem(ItemType(4));
    classList.PutItem(ItemType(5));
    classList.PutItem(ItemType(4));
    classList.PutItem(ItemType(4));
    classList.PutItem(ItemType(8));
    cout << "(original) length: " << classList.GetLength() << endl; classList.ResetList();
    classList.Print();
    classList.ShiftRight();
    cout << "(shifted right) length: " << classList.GetLength() << endl; classList.ResetList();
    classList.Print();
    classList.DeleteItem(ItemType(4));
    cout << "(delete all 4s) length: " << classList.GetLength() << endl; classList.ResetList();
    classList.Print();
    classList.ShiftRight();
    cout << "(shift right) length: " << classList.GetLength() << endl; classList.ResetList();
    classList.Print();
    return 0;
}

【问题讨论】:

    标签: c++ linked-list


    【解决方案1】:

    对于ItemType,您没有采用int 的构造函数。一个简单的解决方法是定义该构造函数:

    ItemType(int v) : value{v} { }
    

    【讨论】:

    • 我可以从 ItemType.h 和 ItemType.cpp 中删除 ItemType(); 并用这个替换它吗?
    • @waleedkhalid 不,你可以保留它;它是默认构造函数。
    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 2019-11-08
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2020-10-07
    相关资源
    最近更新 更多