【发布时间】:2014-06-16 04:42:43
【问题描述】:
我正在设计一个遵循菱形图案的类层次结构,并且我现在正在尝试调试大约一百万个错误;但是,它们中的大多数都是我应该能够弄清楚的简单修复。但是,我很难理解编译器对此的抱怨。
基本上,我从一个简单的实体类开始,它有两个派生类:买家和卖家。反过来,第四类 Retailer 是这两个类的后代——也就是说,它使用多重继承(是的,我知道这会造成什么样的混乱,不幸的是,这正是项目的重点)。
作为参考,我的类的头文件如下:
Entity.h
#pragma once
#include <string>
class Entity {
public:
Entity(std::string &, std::string &, double);
/*Accessor methods for private members*/
std::string getName();
std::string getID();
double getBalance();
/*Mutator methods for private members*/
void setName(std::string &);
void setID(std::string &);
void setBalance(double);
/*Additional methods*/
virtual void list();
virtual void step() = 0;
protected:
/*Private members of the entity class*/
std::string name;
std::string id;
double balance;
};
对于Buyer.h 文件
#pragma once
#include "Entity.h"
#include "Order.h"
#include "Seller.h"
#include <queue>
#include <string>
class Seller;
class Buyer : virtual public Entity {
public:
Buyer(std::string, std:: string, double);
virtual ~Buyer() { }
void addSeller(Seller *);
std::queue<Seller *> getSellers();
void addOrder(Order *);
void list();
void step() override;
protected:
std::queue<Order *> orders;
std::queue<Seller *> sellers;
};
对于Seller.h
#pragma once
#include "Entity.h"
#include "Order.h"
#include "Buyer.h"
#include "Inventory.h"
#include <string>
#include <vector>
class Buyer;
class Seller : virtual public Entity {
public:
Seller(std::string, std::string, double);
virtual ~Seller() {}
void addBuyer(Buyer *);
std::vector<Buyer> getBuyers();
void setInventory(Inventory *);
Inventory * getInventory();
void list();
double fillOrder(Order *);
void step();
protected:
Inventory inventory;
std::vector<Buyer *> buyers;
};
最后是Retailer.h
#pragma once
#include "Buyer.h"
#include "Seller.h"
#include <string>
class Retailer : public Buyer, public Seller {
public:
Retailer(std::string, std::string, double);
virtual ~Retailer() { }
void list();
void step();
};
我在尝试编译这些文件时遇到的大多数错误都与
Buyer.h:9:7: note: candidate expects 1 argument, 0 provided
Seller.h:14:3: note: candidate expects 3 arguments, 0 provided
这很奇怪,因为对于第一行,我什至不必提供参数,而第二行是构造函数的定义....
基本上,我无法理解的是编译器所指的一行代码期望与提供的参数数量不同的代码是什么意思?我应该包括不使用参数的默认构造函数吗?他们的声明方式有问题吗?如有必要,我还可以发布我的 .cpp 文件的代码,尽管编译器错误报告似乎没有多次提及它们。
【问题讨论】:
-
您发布的那些“错误”是与您未发布的其他错误相关的附加信息。尝试发布实际错误。可能您没有在未显示的代码中正确调用 Entity 的构造函数。显示所有与错误相关的代码。
-
其实我之前就意识到了这一点。不幸的是,完整的错误列表比我实际复制到帖子中的要长得多。但是,下面的答案已经帮助我找到了导致编译器运行的大多数代码中的问题。似乎我的大部分问题实际上都是由于未能在彼此中包含一些文件而导致的——换句话说,循环引用失败。
-
在这种情况下,从第一个错误开始并修复它,有时这也会修复由第一个错误引起的其他错误。
标签: c++ constructor virtual multiple-inheritance