相关疑难解决方法(0)

如何使用继承的operator []来防止赋值?

我有一个自定义结构SortedArrayList<T>,根据比较器对其元素进行排序,我想阻止使用operator[].

例:

ArrayList.h

template <typename T> class ArrayList : public List<T> {
    virtual T& operator[](const int& index) override; //override List<T>
    virtual const T operator[](const int& index) const override; //override List<T>
}
Run Code Online (Sandbox Code Playgroud)

SortedLinkedList.h包含以下运算符

template <typename T> class SortedArrayList : public ArrayList<T> {
   public:

   SortedArrayList<T>(const std::function<bool(const T&, const T&)>& comparator);

   T& operator[](const int& index) override; //get reference (LHS)
   const T operator[](const int& index) const override; //get copy (RHS)
}
Run Code Online (Sandbox Code Playgroud)

Test.h

ArrayList<int>* regular = new ArrayList<int>();
ArrayList<int>* sorted = …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance containers list

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

对象成员变量还是继承?

我一直在练习继承,我发现自己在问一个"有一个"关系是什么.

如果我有一个类circleType,我想创建一个类cylinderType,什么派生的区别cylinderTypecircleType,只是包括circleType在定义对象成员cylinderType

class cylinderType :
public circleType
{
public:
    cylinderType();
    ~cylinderType();

private:
    double * height;
};
Run Code Online (Sandbox Code Playgroud)

要么:

class cylinderType
{
public:
    cylinderType();
    ~cylinderType();

private:
    circleType baseOfCylinder;
};
Run Code Online (Sandbox Code Playgroud)

c++ oop polymorphism inheritance

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

从强制班获得原始班

例如,我有三大类:AnimalDogCat; 在哪里Animal是抽象类,并将其属性继承到DogCat。说我的程序,我有一个用户可以输入的任意列表(我正在C#Form上执行此操作)。所以,我店所有的投入,无论他们是类Cat或者Dog,到我List<Animal>

现在,我想从中检索所述实例化的类List<Animal>并检索其原始类,无论是a Cat还是a Dog。有没有办法做到这一点?

c#

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

填充子类的基类向量不起作用

我正在尝试使用具有相同基类的不同子类指针的向量。该向量设置为基类指针,但是添加到该向量的任何内容都无法获得其子类的全部功能。在错误日志中可以看到,它被视为基类,因此未获得扩展功能。

我查看了很多问题,人们说要按照我的方式去做,但是由于某种原因,它没有用。

该代码位于公共仓库中:

https://repl.it/@cubingminer8/inheritance-with-vectors-testing

任何帮助将不胜感激!

编辑:确定,所以我将在c ++ sdl2游戏引擎中将其用于子画面组系统。将有一个基本的Sprite类,其中包含一些基本的东西,例如render和move,而我需要的任何sprite都是它们自己的继承自Sprite的类,它们将具有自己的独特行为,因此虚函数是不切实际的。将有一个sprite组对象,可以将继承自Sprite的对象存储在其中。这样就可以一次全部渲染它们。

如果您曾经使用过pygame,那么它几乎与那里使用的sprite和spritegroup系统相同。 https://www.pygame.org/docs/tut/SpriteIntro.html

#include <iostream>
#include <vector>

class Base {
public:
    char A = 'A';
};

class Sub : public Base {
public:
    char B = 'B';
};

class Sub2 : public Base {
public:
    char C = 'C';
};

int main() {
    std::vector<Base*> List;
    List.push_back(new Sub());
    List.push_back(new Sub2());

    std::cout << List[0]->B << std::endl; // it should be able to print B
    std::cout << List[1]->C << std::endl; // but it is …
Run Code Online (Sandbox Code Playgroud)

c++ polymorphism inheritance class stdvector

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

标签 统计

c++ ×3

inheritance ×3

polymorphism ×2

c# ×1

class ×1

containers ×1

list ×1

oop ×1

stdvector ×1