创建的对象总是未定义,并且在初始化构造函数时期望有标识符

i keep getting undefined for the objects created and expected an identifier when initializing the constructor

本文关键字:构造函数 初始化 期望 标识符 对象 未定义 创建      更新时间:2023-10-16

我已经完成了所有的编码,但我得到错误。对于创建的对象item1和item2,它表示未定义,对于构造函数,它表示期望一个标识符。

Inventory.h

#ifndef Inventory
#define Inventory
class Inventory{
private:
    string name;
    double price;
    int quantity;
public:
    Inventory(); //constructor
    string getName();
    double getPrice();
    int getQuantity();
    void setName(string);
    void setPrice(double);
    void setQuantity(int);
    double totalPrice();
    int decreaseQuantity(int);
    int increaseQuantity(int);
    void displayItemData();
};
#endif

inventory.cpp

#include "Inventory.h"
#include <string>
#include <iostream>
using namespace std;
 Inventory::Inventory(){
    name="null";
    price=0.0;
    quantity=0;
}
string Inventory::getName(){
    return name;
}
double Inventory::getPrice(){
    return price;
}
int Inventory::getQuantity(){
    return quantity;
}
void Inventory::setName(string N){
     N = name;
}
void Inventory::setPrice(double P){
    P = price;
}
void Inventory::setQuantity(int Q){
    Q = quantity;
}
double Inventory::totalPrice(){
    return price*quantity;
}
int Inventory::decreaseQuantity(int x){
    return quantity-x;
}
int Inventory::increaseQuantity(int x){
    return quantity+x;
}
void Inventory::displayItemData(){
    cout<<"NametPricetQuantitytTotal"<<endl;
    cout<<getName()<<getPrice()<<getQuantity()<<totalPrice()<<endl;
}

test.cpp

int main(){
Inventory item1, item2;
item1.setName("Keyboard");
item1.setPrice(23.5);
item1.setQuantity(12);
item2.setName("Speakers");
item2.setPrice(48.0);
item2.setQuantity(4);
item1.displayItemData();
item2.displayItemData();
item1.decreseQuantity(2);
item2.decreseQuantity(5);
item1.increaseQuantity(20);
cout<<"Total price of item 1: "<<item1.totalPrice()<<endl;
cout<<"Total price of item 2: "<<item2.totalPrice()<<endl;
return 0;
}

畸形包含保护。您的#define Inventory意味着预处理器将用空令牌替换Inventory的每个实例。

使用:

#ifndef INVENTORY_H
#define INVENTORY_H
// ...
#endif

使用#pragma once代替header守卫

优点

  • 你的头将始终与任何其他可以定义相同的保护名称兼容。
  • 你不需要做多余的定义。
  • 你不必在每个头文件的开始和结尾都写痛苦的指令。
  • 你可以让你的编译时间更短。

缺点

  • 这是一个非标准的,但被广泛支持的预处理器指令。
结论

如果你想摆脱过去千年来关于header guard的所有冗余要求,不要为严格的标准而烦恼(嘿!标准是为了人,而不是人为了标准),只要使用#pragma once指令,忘记任何关于过时的标题保护的进一步的不愉快。