【问题标题】:C++ explicit type is missing('int' assumed)缺少 C++ 显式类型(假定为“int”)
【发布时间】:2013-10-26 21:12:49
【问题描述】:

您好,我的 C++ 代码有错误。我有 2 个 .cpp 文件和 1 个 .h 文件,我试图从头文件中访问 5 个字符串和 1 个 int 但我收到一条错误消息,提示“缺少显式类型(假定为'int')。

我也有一些其他错误:缺少类型说明符,Shops::Items 重新定义;不同的基本类型,重载函数仅返回类型不同,声明不兼容。

这是我的文件:

UserChoice.h

#include <iostream>
#include <string>

using namespace std;

#ifndef USERCHOICE_H
#define USERCHOICE_H

class Shops
{
public:

    double Items(string, string, string, string, string, int);

    int main()
    {
        std::cout << newItem1;
    }

private:
    string newItem1;
    string newItem2;
    string newItem3;
    string newItem4;
    string newItem5;
    int newItems;

};
#endif

Items.cpp

#include "UserChoice.h"

Shops::Items(string Item1, string Item2, string Item3, string Item4, string Item5, int     Items)
{
    newItem1 = Item1;
    newItem2 = Item2;
    newItem3 = Item3;
    newItem4 = Item4;
    newItem5 = Item5;
    newItems = Items;
}

Source.cpp

#include "UserChoice.h";
#include <string>

int main()
{
    string Item1;
    string Item2;
    string Item3;
    string Item4;
    string Item5;
    int items;

    std::cout << "What what you like? Chicken, Meat, Fish, Carrot or Apple?\n";
    std::cin >> Item1;
    std::cout << "\nAnything else?\n";
    std::cin >> Item2;
    if(Item2 == "nothing else")
    {

    }
    std::cout << "\nAnything else?\n";
    std::cin >> Item3;
    std::cout << "\nAnything else?\n";
    std::cin >> Item4;
    std::cout << "\nAnything else?\n";
    std::cin >> Item5;
    std::cout << "\nAnything else?\n";
}

错误线

Shops::Items(string Item1, string Item2, string Item3, string Item4, string Item5, int Items)

所有的代码还没有完成,所以我希望你能帮助我找到并修复这些错误。 在此先感谢您,如果您需要更多信息,请询问我。

【问题讨论】:

  • 我相信丹尼尔已经回答了你的问题。一个建议:不要在你的类和你的函数签名中使用 5 个字符串,为什么不使用 vector
  • Raja 提出了一个很好的观点。传入 vector 将允许您在不影响方法签名的情况下拥有任意数量的项目,并且您将能够通过使用 vector size() 确定您拥有多少项目,而无需传入项目计数。
  • 当我的一个构造函数中有错字时,我有时会收到此错误。

标签: c++ class header compiler-errors int


【解决方案1】:

您在Items.cpp 的定义中缺少返回类型:

double Shops::Items(string Item1, string Item2, string Item3, string Item4, string Item5, int Items)
{
    //...
}

您还需要为Shops::Items 和类的main 函数返回一些值。

关于命名:在类中复制“普通”main 函数看起来很奇怪,并且将参数命名为与类的名称完全相同也看起来很奇怪。它确实有效,但我会在代码审查 FWIW 中标记它。 :)

【讨论】:

  • 另外,您不应该将最后一个参数命名为Items,因为如果您尝试使用该变量,这肯定会与您的类方法Items(...) 发生冲突。
  • 谢谢!这解决了它。
  • @MichaelSchlottke 看起来很奇怪,但实际上是允许的,不一定会发生冲突,即任何潜在的冲突都可以通过使用struct Items::Items 来解决。
  • @DanielFrey 感谢您指出这一点。也许我应该说“这肯定会降低代码的可读性”:)
【解决方案2】:

您在 Shops::Items 的实现文件 (cpp) 中缺少返回类型,根据您在头文件中的内容,这将是双精度。您遇到的其他错误很可能是相关的。

在你的类中有一个名为 main 的方法有点令人不安,因为它通常是用于你的程序入口点的函数名。

【讨论】:

    猜你喜欢
    • 2013-11-22
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2015-05-02
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多