0 c++ inheritance pointers memory-leaks class
好的,所以我有两个类,在代码中按顺序称它们为A和B. B类将A类实例化为数组,B类也有一个错误消息char*变量,A类必须在发生错误时设置.我创建了一个带有纯虚函数的第三个类,用于在B中设置errorMessage变量,然后使B成为该第三个类的子元素.A类创建一个指向第三个类的指针,称之为C - 当B初始化A对象的数组时,它循环遍历它们并调用A中的函数将A的指针设置为C--它将"this"传递给该函数,然后A将指向C的指针设置为"this",并且由于C是B的父级,A可以设置C-> errorMessage(我必须这样做,因为A和B在编译时不能同时意识到对方时间).
但是,无论如何它工作正常,当我将命令行参数传递给main(int,char**)时,除非我将七个,八个或十二个以上的参数传递给它,否则它会起作用...我将其缩小(通过注释)出来的行代码,在A中,它将指针指向C,设置为由B传递给它的值.这对我没有意义......我怀疑是内存泄漏或其他什么,但它似乎错了,我不知道如何修复它...另外我不明白为什么特别是七,八,十二个以上的参数不起作用,1-6和9-12工作正常.
这是我的代码(剥离) -
//class C
class errorContainer{
public:
virtual ~errorContainer(){ }
virtual void reportError(int,char*)=0;
};
//Class A
class switchObject{
void reportError(int,char*);
errorContainer* errorReference;
public:
void bindErrorContainer(errorContainer*);
};
//Class A member function definitions
void switchObject::reportError(int errorCode,char* errorMessage){
errorReference->reportError(errorCode,errorMessage);
}
void switchObject::bindErrorContainer(errorContainer* newReference){
errorReference=newReference; //commenting out this line fixes the problem
}
//Class B
class switchSystem: public errorContainer{
int errorCode;
char* errorMessage;
public:
switchSystem(int); //MUST specify number of switches in this system.
void reportError(int,char*);
int errCode();
char* errMessage();
switchObject* switchList;
};
//Class B member function definitions
switchSystem::switchSystem(int swLimit){
int i;
switchList=new (nothrow) switchObject[swLimit];
for(i=0;i<swLimit;i++){
switchList[i].bindErrorContainer(this);
}
errorCode=0;
errorMessage="No errors.";
}
void switchSystem::reportError(int reportErrorCode,char* reportErrorMessage){
int len=0,i;
errorCode=reportErrorCode;
if(errorMessage){
delete[] errorMessage;
}
while(reportErrorMessage[len]!='\0'){
len++;
}
errorMessage=new char[len];
for(i=0;i<=len;i++){
errorMessage[i]=reportErrorMessage[i];
}
}
int switchSystem::errCode(){
return errorCode;
}
char* switchSystem::errMessage(){
return errorMessage;
}
Run Code Online (Sandbox Code Playgroud)
谁知道我在这里做错了什么?它正在惹恼我...我似乎无法解决它.
---编辑---好吧,我已经设置了我这样做的方式,我可以在main()中使用它
int main(int argc,char** argv){
switchSystem sw (2)
sw.switchList[0].argumentCount=2;
sw.switchList[1].argumentCount=0;
sw.switchList[0].identifier="a";
sw.switchList[1].identifier="switch";
sw.init(argc,argv);
if(sw.errCode()>0){
cout<< "Error "<< sw.errCode()<< ": "<< sw.errMessage()<< endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序应该读取命令行参数并处理用户定义的"开关" - 就像大多数命令行程序处理开关一样,但不是在main的开头测试所有这些,我想尝试编写一个类和一些函数为我做 - 创建一个switchSystem对象,其中包含开关数,设置它们的标识符,是否接受参数,然后将命令行参数传递给"init()"进行排序.那么测试就好了,
if(sw.isSet("switch")){ ... } 等等
你似乎很可怕:
while-loop来计算字符串的长度; 你没听说过strlen()吗?std::string?char数组难以解释.