C++错误:CA 时无效使用'AppleFarmer::AppleFarmer'

C++ error: invalid use of 'AppleFarmer::AppleFarmer' when ca

本文关键字:AppleFarmer 无效 错误 CA C++      更新时间:2023-10-16

我收到错误"错误:AppleFarmer::AppleFarmer使用无效。我不知道为什么我会收到此错误,因为我没有尝试将任何输入传递到我的构造函数中。我的 .h 文件可能有问题吗?我做错了什么才能得到这个错误?我有三个不同的文件,当我正在为.cpp文件执行#include时,我也可能遇到将代码链接在一起的问题。我不确定我的代码是否除了此错误之外还能工作,但我被困在此错误上。

苹果农主.cpp

#include<iostream>
#include "appleFarmer.cpp"
int main(){
    AppleFarmer m;
    int harvest;
    int demand;
    m.AppleFarmer();
    while(m.endOfMonth()==false){
        cout<<"Enter a harvest amount:"<<endl;
        cin>>harvest;
        m.harvestApples(harvest);
        cout<<"Enter a demand:"<<endl;
        cin>>demand;
        m.sellApples(demand);
        cout<<"Apple Inventory: "<<m.getInventory()<<endl;
        m.updateCurrentDay();
    }
    return 0;
}

苹果农.cpp

#include "appleFarmer.h"
#include "<iostream>
using namespace std;
AppleFarmer::AppleFarmer(){
    for(int i=0;i<30;i++){
        sales[i]=0;
        harvest[i]=0;
    }
}
bool AppleFarmer::sellApples(int demand){
    if(demand<= inventory){
        sales[currentDay]=demand;
        inventory=inventory-demand;
    }
    else{
        sales[currentDay]=0;
    }
}
void AppleFarmer::harvestApples(int dayHarvest){
    harvest[currentDay]= dayHarvest;
    inventory=inventory+dayHarvest;
}
bool AppleFarmer::endOfMonth(){
    if (currentDay=maxDays){
        return true;
    }
    else{
        return false;
    }
}
int AppleFarmer::updateCurrentDay(){
    currentDay=currentDay+1;
}
int AppleFarmer::getInventory(){
    return inventory;
}
double AppleFarmer::calculateAverageHarvest(){
}
double calculateAverageSales(){
}
void AppleFarmer::printSales(){
}
void AppleFarmer::printHarvest(){
}

苹果农夫

#ifndef APPLEFARMER_H
#define APPLEFARMER_H
class AppleFarmer
{
    public:
        AppleFarmer();
        bool sellApples(int);
        void harvestApples(int);
        bool endOfMonth();
        int updateCurrentDay();
        int getInventory();
        double calculateAverageHarvest();
        double calculateAverageSales();
        void printSales();
        void printHarvest();
    private:
        int sales[30];
        int harvest[30];
        int maxDays = 30;
        int currentDay = 0;
        int inventory = 0;
};
#endif 

在C++中,您不会在对象上调用构造函数。这发生在对象创建时。该行

m.AppleFarmer();

不需要。构造函数在这里隐式调用:

AppleFarmer m;
您需要

包含appleFarmer.h而不是appleFarmer.cpp因为头文件(扩展名为.h)包含声明,而.cpp文件包含实现。

然后你还需要删除 m.AppleFarmer(); 因为在声明期间调用构造函数(AppleFarmer m 文本行)。