gpt4 book ai didi

C++错误获取派生类显示抽象类中的变量,该变量与派生类的父类具有聚合关系

转载 作者:行者123 更新时间:2023-11-28 06:12:23 27 4
gpt4 key购买 nike

我正在尝试让我的派生类 (humanplayer) 使 abstract(Vector) 的变量成员函数等于“hi”,以便我可以显示它,但编译器的行为很奇怪,并说 EXC_BAD_ACCESS(code=EXC_I386_GPFLT ).

这是我的头文件:

#ifndef __testing_more_stuff__vector__
#define __testing_more_stuff__vector__

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Vector{//abstract class
public:
void setName(string name_holder);
virtual void test()=0;
protected:
string name;

};

class player{//base class that has an aggregation relationship with vector

protected:
Vector *molo;
};


class humanplayer:public player//derived class of player
{
public:
void play();
};

#endif

这是我的实现文件:

#include "vector.h"

void Vector::setName(string name_holder)
{
name=name_holder;
cout<<name<<endl;
}

void humanplayer::play()
{
molo->setName("hi");//since humanplayer inherits from player it should be able to set name to hi and print it out
}

这是我的测试/主文件:

#include "vector.h"


int main()
{
humanplayer x;

x.play();
}

最佳答案

humanplayer::play() 中你说:

molo->setName("hi")

但是,moloVector类型,是一个抽象基类指针。

一些事情:

  1. 您没有派生自 Vector 的任何具体类
  2. 永远不要将 molo 初始化为 molo = new VectorDerivedClass()
  3. 您没有将 molo 默认初始化为 nullptr,也没有检查它。您的 string 分配是未定义的行为。

您必须有一个来自 Vector 的具体派生类。在你尝试用它做任何事情之前,你必须用 new 实例化指针。

关于多态性的好处是你可以有一个指向抽象基类的指针。该指针可以分配给任何动态分配的派生类。实际上,指针强制执行一个接口(interface);派生类保证在抽象基类中实现纯虚函数(并继承您在基类中提供的定义)。

缺点是您必须从类继承,并且调用virtual 函数必须通过虚拟表(vtable),这是一种间接方式,速度稍慢。

关于C++错误获取派生类显示抽象类中的变量,该变量与派生类的父类具有聚合关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30992207/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com