Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c++;继承问题和指针。试图使用指针访问子类,但找不到该函数 我在C++中编码,并且在继承和指针方面有问题。我想知道扔枪的物体(枪)上有多少个凹口,但它说人没有这样的功能。枪是儿童类的人,所以我有点困惑。这是密码_C++_Pointers_Inheritance - Fatal编程技术网

c++;继承问题和指针。试图使用指针访问子类,但找不到该函数 我在C++中编码,并且在继承和指针方面有问题。我想知道扔枪的物体(枪)上有多少个凹口,但它说人没有这样的功能。枪是儿童类的人,所以我有点困惑。这是密码

c++;继承问题和指针。试图使用指针访问子类,但找不到该函数 我在C++中编码,并且在继承和指针方面有问题。我想知道扔枪的物体(枪)上有多少个凹口,但它说人没有这样的功能。枪是儿童类的人,所以我有点困惑。这是密码,c++,pointers,inheritance,C++,Pointers,Inheritance,旁注:错误在main中是p->getnotches(),它表示(类“Person”没有成员“getnotches”) 在这个表达式中 p->getnotches() 由于此声明,指针p的静态类型为Person* Person *p; 因此,编译器在类Person中搜索函数getnotches,但没有找到它,因为该类没有这样的函数 class Person { private: char *name; public: Person(); Person(strin

旁注:错误在main中是p->getnotches(),它表示(类“Person”没有成员“getnotches”)

在这个表达式中

p->getnotches()
由于此声明,指针
p
的静态类型为
Person*

Person *p;
因此,编译器在类
Person
中搜索函数
getnotches
,但没有找到它,因为该类没有这样的函数

class Person
{
private:
    char *name;

public:
    Person();
    Person(string name);
    virtual string getName();
    virtual ~Person();
};

您需要使用
dynamic\u cast
(如果编译器支持)或
reinterpret\u cast
与指针一起使用。

尽管您有一个Gunslinger对象,但您将其视为Person对象,Person类没有getnotches方法。我不知道你为什么想让一个人成为枪手的目标。只要用投枪者的“枪”而不是人*“p”


cout编译器不会在类层次结构中查找可能在其他类中定义的函数。在
Person*
类型的指针上,只能从
Person
类调用函数,而不能调用其他任何函数。注意,您可能会混合使用std::string和cstring。你应该移除cstring includein为了解决这个问题我必须把指针指向持枪歹徒吗?或者其他什么solutions@Kninja99是的,例如,您需要使用dynamic_cast。或者reinterpret_castOne在对层次结构中的相关类进行强制转换时,不应使用
reinterpret_cast
。您必须使用
static\u cast
dynamic\u cast

    #ifndef GUNSLINGER_H
#define GUNSLINGER_H
#pragma once
#include "Person.hpp"
#include <cstring>
#include <string>

class Gunslinger : public Person
{
private:
    char *name;
    int notches;
    double drawTime;

public:
    Gunslinger(string n, int cylinders);
    int getnotches();
    virtual string getName();
    ~Gunslinger();
};
#endif


    #include "Gunslinger.hpp"

Gunslinger::Gunslinger(string n, int clinders)
{
    name = new char[n.length() + 1];
    strcpy(name, n.c_str());
    notches = clinders;
}

string Gunslinger::getName()
{
    return name;
}

int Gunslinger::getnotches()
{
    return notches;
}

Gunslinger::~Gunslinger()
{
    delete[] name;
}

p->getnotches()
Person *p;
class Person
{
private:
    char *name;

public:
    Person();
    Person(string name);
    virtual string getName();
    virtual ~Person();
};