我在用cpp编写简单的商店程序。我有三门课:商店,客户,桶。商店是斗牛的家长班。商店有客户向量,每个客户都有自己的桶。我对# include 's有问题。我必须在Shop.h中包含Client.h,这样商店就可以看到客户的向量,但出于类似的原因,我似乎也必须在Clinet.h中包含Bucket.h。这会产生一个问题: Shop之前包含了桶,所以我得到了“基类未定义”错误。我怎么才能把这事做好?
Shop.h
#pragma once
#include <vector>
#include <string>
#include "functions.h"
#include "Client.h"
class Shop {
protected:
std::vector<int> quantities;
std::vector<std::string> products;
std::vector<float> prices;
private:
std::vector<Client*> clients;
int loggedClient;
public:
Shop();
~Shop();
int readProducts();
int loadClientsBase();
int checkLoginData(std::string log, std::string pass, int *logged);
int checkIfSameLogin(std::string log);
int addClient();
void login();
void logout();
int sell();
virtual void display();
void displayLoggedClient();
int saveHistory();
};Client.h
#pragma once
#include "Bucket.h"
class Client
{
private:
float money=0.0;
Bucket bucket;
std::string login;
std::string password;
std::string description;
public:
Client();
~Client();
void addLoginData(std::string log, std::string pass, std::string desc, float mon);
std::string getLogin() { return login; };
std::string getPassword() { return password; };
std::string getDescription() { return description; };
float getMoney() { return money; };
void addLogin(std::string log);
void addPassword(std::string pass);
void addDescription(std::string desc);
void addMoney(float m);
void addToBucket(std::string prod, int quant, float price);
void displayBucket();
Bucket getBucket() { return bucket; };
friend std::ostream& operator<<(std::ostream& os, Client& client);
};Bucket.h
#pragma once
#include <vector>
#include <string>
#include "Shop.h"
class Bucket : public Shop
{
public:
Bucket();
~Bucket();
void addProduct(std::string name, int amount, float price);
void deleteProduct();
void display();
std::string getProduct(int i);
int getQuantity(int i);
float getPrice(int i);
int getNumberOfProducts() { return products.size(); };
void clearBucket();
};发布于 2020-06-01 11:47:11
Bucket.h包括Shop.h,包括Client.h,包括Bucket.h。等等,直到永远。这是一个循环依赖关系。
Shop.h不需要包含Client.h,它只需要转发声明Client类:
#pragma once
#include <vector>
#include <string>
#include "functions.h"
// #include "Client.h"
class Client; // Forward declaration of the class, that's needed for pointers to it
class Shop {
...
};Shop的实现需要Client的完整定义,所以Shop源文件(Shop.cpp?)需要包括Client.h。
发布于 2020-06-01 11:44:14
为了解决眼前的问题,您需要在Client中转发声明Shop.h类。但是,您在这里构建的类层次结构至少可以说是令人困惑的,例如,每个Client都拥有一个Shop,将类层次结构更改为更合理的结构应该可以完全消除问题。
https://stackoverflow.com/questions/62131292
复制相似问题