小编use*_*729的帖子

无法将"派生"转换为其私有基类"base"

我在尝试创建一个从一个继承自定义纯虚函数的类的类继承的对象时遇到错误.我不确定是什么问题.我知道我需要覆盖派生类中的纯虚函数,但它不起作用.我只想覆盖我的ProduceItem类中的函数而不是我的Celery类,因为我希望Celery类继承ProduceItem中的重写方法.

在主要:

    GroceryItem *cel = new Celery(1.5); //Cannot cast 'Celery' to its private base class GroceryItem


    class GroceryItem
    {
    public:
        virtual double GetPrice() = 0;
        virtual double GetWeight() = 0;
        virtual std::string GetDescription() = 0;

    protected:
        double price;
        double weight;
        std::string description;

    };
Run Code Online (Sandbox Code Playgroud)

ProduceItem头文件:

#include "GroceryItem.h"

class ProduceItem : public GroceryItem
{
public:
    ProduceItem(double costPerPound);
    double GetCost();
    double GetWeight();
    double GetPrice();
    std::string GetDescription();
protected:
    double costPerPound;
};
Run Code Online (Sandbox Code Playgroud)

ProduceItem.cpp文件:

#include <stdio.h>
#include "ProduceItem.h"
ProduceItem::ProduceItem(double costPerPound)
{
    price = costPerPound * weight; …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance

19
推荐指数
2
解决办法
1万
查看次数

有条件地将std :: string分配为引用

我有一些代码是正在运行的较大函数的一部分。但是,为了优化它并消除不必要的字符串复制,我想用引用重写此代码。我的代码依赖于GreaterStr是比smallStr更长的字符串。我想用引用重写它,但似乎无法正常工作。如果我尝试在没有显式初始化它们的情况下创建更大的引用和更小的引用,则编译器会告诉我需要在声明时对其进行初始化。如果我尝试将其作为if语句中的临时变量,则最终两个变量都引用同一字符串。

最好的解决方案是什么?

//str1 and str2 are std::strings
std::string largerStr, smallerStr;

if(str1.length() > str2.length()) {
    largerStr = str1;
    smallerStr = str2;
} else {
    largerStr = str2;
    smallerStr = str1;
}
Run Code Online (Sandbox Code Playgroud)

c++

1
推荐指数
1
解决办法
64
查看次数

标签 统计

c++ ×2

inheritance ×1