繁体   English   中英

C++ 多个重载实例 function 与创建 header 文件时的参数列表匹配

[英]C++ more than one instance of overloaded function matches the argument list when creating a header file

在我的程序的主文件中,我有以下声明

int main()
{
    Customer c;
    Part p;
    Builder b;
    auto partsVec =  readpartFile();
    auto customerVec = readcustomerFile();
    auto builderVec = readbuilderFile();

    fexists("Parts.txt");
    complexity(c, partsVec);
    robotComplexity(partsVec,customerVec);
    writeFile(buildAttempt(b, complexity(c, partsVec), variability(customerVec, builderVec)));
}

我的 header 文件包含以下内容

vector<Part> readpartFile();

vector<Customer> readcustomerFile();

vector<Builder> readbuilderFile();

float complexity(const Customer& c, const std::vector<Part>& parts);

void robotComplexity(vector<Part> vecB, vector<Customer> vecC);

double variability(const vector<Customer>& customerList, const vector<Builder>& builderList);

vector<double> buildAttempt(Builder b, double variaiblity, double complexityRobot);

void writeFile(vector<double> build);

除 robotsComplexity 外,所有功能都链接在一起。 我在 main 中声明此 function 会产生以下错误。

more than one instance of overloaded function "robotComplexity" matches the argument list: -- function "robotComplexity(const std::vector> &parts, const std::vector> &customers)" -- function "robotComplexity(std::vector> vecB , std::vector> vecC)" -- 参数类型为: (std::vector>, std::vector>)

我不知道为什么我会收到这个错误或如何解决它

您在 header 中的声明与定义(也用作声明)之间存在不匹配:

  • void robotComplexity(vector<Part> vecB, vector<Customer> vecC);
  • void robotComplexity(const vector<Part>& vecB, const vector<Customer>& vecC);

尽管参数名称可能不匹配,但类型不应该匹配,否则,您会创建另一个重载。

Jarod42 的回答非常正确,但我想补充一点,并为未来的 C++ 编码提供有用的方法。

当 function 签名不同时,编译器不会报错。 充其量,您将收到一个神秘或难以阅读的 linker 错误。 这在 inheritance 和虚拟功能中尤其常见。 更糟糕的是,有时它们会起作用,但实际上调用了一个新的 function,其子 class 上的签名与基本 class 不匹配。

C++11(和更新版本)中有一个关键字叫做override 以下是关于它们的关键字作用的更深入讨论: OverrideKeywordLink

When this keyword is used on a virtual function, it becomes a compile error when the intended virtual function override does not match the base class function signature. 此外,它给出了一个非常易于理解的原因,说明为什么没有发生 function 覆盖。

您在评论中提到“为什么 const 使它与众不同”?答案是这一切都归结为 function 签名。考虑 class 中的这两个函数。

class MyClass {
    int CalculateSomething();
    int CalculateSomething() const;
}

const 实际上改变了 function 签名。 它们被认为是两种不同的功能。 底线是,总是试图让错误编译错误超过运行时错误。 使用可以保护您免受一些存在的部落 C++ 知识陷阱的关键字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM