【问题标题】:C++ output operator for abstract class抽象类的 C++ 输出运算符
【发布时间】:2014-11-22 22:10:38
【问题描述】:

所以我有一个带有字段名称和价格的抽象类 Product。有几个类继承自 Product,Product 之所以是抽象的,是因为这些子类必须实现这个功能(在 Product 中定义):

 virtual std::string getCategory()=0;

类别不是一个字段,它只取决于我们拥有哪个子类,在某些情况下还取决于价格。

现在我想要 Product 的子类的输出运算符,但由于我只想打印名称和价格,所以我在 Product.h 中执行了此操作:

 friend std::ostream& operator<<(std::ostream& os, const Product& secondOperand);

这个在 Product.cpp 中:

 ostream& operator<<(ostream& outputStream, Product& secondOperand){
     outputStream << "["<<secondOperand.getName()<<" "<<secondOperand.getPrice()<<"]"<<endl;
     return outputStream;
 }

现在我在 Visual Studio 中收到此错误:

Error C2259: 'Product' : cannot instantiate abstract class

我不想为每个子类实现这个输出(因为我必须逐字复制所有不理想的东西)。另外,我开始时 Product 不是纯虚拟的,但后来我遇到了 getCategory() 函数的链接器错误...

【问题讨论】:

  • 在哪里你得到错误?是完整的错误输出吗?
  • 您为声明显示const Product&amp;,但为实现显示Product&amp;。这种不匹配可能无法编译。但此外,它让我怀疑你在其他地方有一个错误,例如你通过值传递 Product 从而使编译器认为你想要实例化一个,从而导致有问题的编译错误。
  • 不是重复的,因为他希望他的子类有不同的输出。该错误是我唯一的编译器错误。它位于 operator
  • 方法没有问题...粘贴完整代码

标签: c++ class output operator-keyword abstract


【解决方案1】:

方法没有错,这是一个编译和运行的示例......

#include <string>
#include <iostream>

using namespace std;

class Product
{
public:
    friend std::ostream& operator<<(std::ostream& os, const Product& secondOperand);
    virtual ~Product() = 0;

    string getName() { return "Product Name"; }
    string getPrice() {return "£1.00"; }
    virtual std::string getCategory()=0;
};

ostream& operator<<(ostream& outputStream, Product& secondOperand){
     outputStream << "["<<secondOperand.getName()<<" "<<secondOperand.getPrice()<<"]"<<endl;
     return outputStream;
 }

Product::~Product() {}

class DerivedProduct : public Product
{
public:
    DerivedProduct() {}
    std::string getCategory() { return "Derived getCategory()"; }
};

int main(int argc, char *argv[])
{
    DerivedProduct d;
    cout << d.getCategory() << endl;
    cout << d << endl;
    return 0;
}

【讨论】:

  • 谢谢,这让我明白我只是看错了部分!我的错误似乎可以通过包含 来解决,尽管听起来很愚蠢......
猜你喜欢
  • 1970-01-01
  • 2012-06-16
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 2012-12-04
  • 2016-07-15
相关资源
最近更新 更多