首页 > 解决方案 > 函数调用错误中的参数过多

问题描述

我正在创建一个类的对象并编写了一个构造函数并正在添加一个对象。我相信我有足够的函数变量,但它说我有太多的参数。我不明白它为什么这么说。

我尝试重做我的构造函数和代码,但我继续遇到同样的错误。我最终希望能够克隆该对象,但我也不知道该怎么做。

#include "pch.h"
#include <iostream>
#include <string>

using namespace std;


class Animal {
public:
    Animal() {};

    Animal(string uAName, string uASize, string uAColor, int uANumLegs)
        : aName(uAName), aSize(uASize), aColor(uAColor), numLegs(uANumLegs) {};

    void printAnimal(Animal) {
        cout << "Your animal is: " << aName << endl;
        cout << "The animal size is: " << aSize << endl;
        cout << "The animal Color is: " << aColor << endl;
        cout << "The animal has " << numLegs << " legs" << endl;
    }

    virtual Animal* clone() { return (new Animal(*this)); }

    void aClone(Animal* nAnimal) {
        Animal* cal = nAnimal->clone();

    }

private:
    string aName = "";
    string aSize= "";
    string aColor = "";
    int numLegs = 0;


    };



int main()
{
    Animal newAnimal();

    string uName = "Bear";
    string uSize = "Large";
    string uColor = "Black";
    int uLegs = 4;

    newAnimal(uName, uSize, uColor, uLegs);

}

标签: c++function

解决方案


Animal newAnimal();函数声明,而不是变量声明(由于“最令人烦恼的解析”)。因此调用newAnimal(uName, uSize, uColor, uLegs);试图调用具有 4 个值的 0 参数函数,因此出现错误。

即使您修复了该声明(通过删除括号),您的代码仍然无法编译,因为newAnimal(uName, uSize, uColor, uLegs);那时会尝试operator()newAnimal对象上调用,但您的类没有实现operator().

要调用您的类构造函数,您需要main()改为:

int main() {
    string uName = "Bear";
    string uSize = "Large";
    string uColor = "Black";
    int uLegs = 4;
    Animal newAnimal(uName, uSize, uColor, uLegs);
}

推荐阅读