简体   繁体   English

C ++多态性,虚函数错误

[英]C++ polymorphism, virtual functions error

I got the problem with virtual methods of my C++ projects. 我在C ++项目的虚拟方法中遇到了问题。

First of all i got the class graphics which presents: 首先,我得到了呈现以下内容的班级图形:

#pragma once
class gameGraphics
{
public:
    gameGraphics();
    ~gameGraphics();
    virtual void paint();
};

and i got two classes, first one : 我有两节课,第一节课:

class brick 
    : public gameGraphics
{
protected:
    int R, G, B;
    bool ifDelete;
public:
    brick();
    ~brick();
    virtual void paint(int x, int y);
};

And the second one: 第二个:

class superBrick :
    public brick, public gameGraphics
{
private:
    int bonusType;
public:
    superBrick();
    ~superBrick();
    void paint(int x, int y);
};

Then im trying to paint objects of this two classes, when my projects runs it shows error: "Unhandled exception at 0x74D3CB49 in project.exe: 0xC0000005: Access violation executing location 0x00000000.", while trying paint function for superBrick object. 然后,我尝试绘制这两个类的对象时,当我的项目运行时,它显示错误:“尝试为superBrick对象绘制函数时,“ project.exe中0x74D3CB49的未处理异常:0xC0000005:执行位置0x00000000的访问冲突。”

for (int i = 0; i < WIDTH; i++)
{
    for (int k = 0; k < LENGTH; k++)
    {
        temp = &table[k][i];
        temp->paint(k, i);
    }
}

I dont know what is the reason of this error, i think i did the Polymorphism good. 我不知道此错误的原因是什么,我认为我所做的多态性很好。

Sorry for my english, thanks for reading and help! 对不起,我的英语,谢谢您的阅读和帮助!

Have a good night! 祝你有一个美好的夜晚!

EDIT: 编辑:

class of table here: 表格类别:

class gameTable : public gameGraphics
{
private:
    brick** table;
public:
    gameTable();
    ~gameTable();
    void paint(int CordX, int cordY);   
};

I believe this is the source of your problem 我相信这是您问题的根源

    temp = &table[k][i];

You can't have polymorphism with an array of objects because they would all be of the same class. 您不能对对象数组具有多态性,因为它们都属于同一类。

You've omitted the definition of table but it probably should be an array of pointer that can reference different classes with the same parent class. 您已经省略了表的定义,但是它可能应该是一个指针数组,该指针数组可以引用具有相同父类的不同类。

Access violation executing location 0x00000000 . 访问冲突执行位置0x00000000。 This means you are dereferencing a null ptr ( a pointer of address 0. So the access violation is that you can't reference memory at location 0. Either table is null or table[k] is null. Make sure table is initialized with brick ptrs. 这意味着您要取消引用一个空ptr(地址为0的指针。因此,访问冲突是您无法在位置0处引用内存。table为null或table [k]为null。请确保使用Brick初始化了table师生比。

Also check "Cheers and hth" comments for good coding suggestions. 还要检查“干杯和hth”注释,以获得良好的编码建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM