[英]dynamic object pointer array C++
我想创建一个指针数组,该指针数组包含该类的实例的地址,因此,当我调用scanner
函数时,它将搜索具有相同pcode
对象并将其打印出来。 我确实做到了,但是现在当我尝试使用其他继承的类对象时,出现“内存访问冲突”,并且无法通过基本静态扫描功能访问继承的类函数。
很抱歉这里是我的代码
using namespace std;
class product{
public:
product();
product(long&,string&);
void const printer();
void setCode();
void getCode(long);
void static scanner();
static product *point; //when this was static did compile but not now
static int a;
private:
string pname;
long pcode;
};
class PrepackedFood:public product{
//snip
private:
double uPrice;
};
class FreshFood:public product{
//snip
private:
double weight;
double pricepk;
};
product.cpp
product *product::point=new product [15]; //when i use try to use dynamic cant
int product::a(0);
product::product(){
pcode=0;
pname="unknown";
point[a]= this; //here works for normal arrays not now
a++;
}
product::product(long& c,string&n){
pcode=c;
pname=n;
}
void product::scanner(){
long a;
int i=0;
while(i<3){
if (point[i]->pcode==a){
point[i]->printer();
break;
}
i++;
}
}
void product::setCode(){
cout<<"enter product name\n ";
cin>>pname;
cout<<"enter product code _____\b\b\b\b\b\a";
cin>>pcode;
}
//blah blah for other members
main.cpp
#include "product.h"
#include <iostream>
int main(){
int i=0;
cout<<"enter fresh foods"<<endl;
FreshFood f[3];
for(int a=0;a<3;a++)
f[i].setCode();
product::scanner();
return 0;
}
是内存地址问题还是其他完全不同的东西? 为什么scan{this->print()}
调用基本函数? 有没有办法调用继承的print()
函数?
好了,既然我终于简化了您的问题文本,下面是答案:
void const printer();
这不会编译。 如果要调用某个函数以调用最派生类型的函数,则必须将该函数标记为virtual
。 同样, const
在名称之后。 void setCode();
直接从控制台读取商店产品通常不是一个好主意。 做一个项目是工作,而项目不解析数字。 外部函数应解析输入。 static product *point;
这可能应该替换为std::vector<product*>
。 这是指向各个产品的动态指针数组。 指向每个产品的指针允许virtual
函数的多态性按照您希望的方式工作。 product *product::point=new product [15];
创建一个由15个product
对象组成的数组。 并非PrepackedFood
或任何其他类型的物体,这些只是 products
。 没有更多或更少。 另外,您正在泄漏此内存。 使用vector
point[a]= this;
因为point[a]
是product
,并且this
是一个指针,所以它甚至不编译。 product::product(long& c,string&n)
此函数不注册产品。 与此相关的所有产品均未在您的阵列中注册,也无法找到。 幸运的是,您没有使用它。 void getCode(long) {
我什至不知道这段代码是做什么的,这太糟糕了。 void product::scanner(){
使用for循环而不是while循环,这很令人困惑。 另外,您只扫描制造的前三个项目,它可能应该扫描所有制造的项目。 使用vector
会有所帮助。 product
被销毁(这是非常普遍的),那么整个设计将失败,并且修复将非常复杂。 我不知道您在做什么,但我建议您立即停止。 我明白了吗?
我认为您需要尝试使用容器来实现“数组”。 std :: list将是一个好的开始。 看一下本文 ,向下滚动至带有for循环的示例,这应该可以帮助您清理代码并解决内存访问问题。 请记住,您可以将整个对象存储在列表中,而不仅仅是指向它们的指针。
另外,您可以尝试将数据与代码分离。 尝试对数据使用结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.