创建的对象总是未定义,并且在初始化构造函数时期望有标识符
i keep getting undefined for the objects created and expected an identifier when initializing the constructor
我已经完成了所有的编码,但我得到错误。对于创建的对象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
指令,忘记任何关于过时的标题保护的进一步的不愉快。
相关文章:
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 我们可以用参数化构造函数初始化结构的数组吗?
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 类内初始化与构造函数初始化列表的顺序
- 通过 C++ 中的重载构造函数初始化未知类型的变量
- 使用复制构造函数初始化 new[]
- 如何从子类的构造函数初始化父类的私有成员
- 在构造函数初始化列表中使用 std::variant
- 使用构造函数初始化结构还是在之后设置其值更好?
- C++ 没有匹配的构造函数初始化 []
- 我正在使用dev c ++,但收到错误(C++98'array'必须由构造函数初始化)
- 使用所述填充构造函数初始化向量中的向量
- 如何同时创建一个具有两个或多个构造函数初始化的对象
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 这是使用构造函数初始化数组对象的最佳方法吗?
- 内置类型的构造函数初始化
- 构造函数初始化和对象损坏