我的第一篇文章在这里!我多年来一直在使用这个网站作为参考,并找到常见问题的解决方案。不幸的是,我遇到的这个问题还没有在这里找到!所以在这里。我一直在做一段时间的项目。我的程序有几千行代码,所以我不会在这里发布。基本上,我有一个我希望将父类更改为已在我的代码中已经初始化的子类。我不确定这是否可行,或者是否是良好的代码练习。但是我会让你们成为那个评委!这里是我面临的问题:C++更改子类中的父类
#include <stdio.h>
class Base
public:
int data;
Base(int);
};
class Child : public Base
{
public:
Child(void);
void run(Base*);
};
Base::Base(int var)
{
data=var;
}
void Child::run(Base* base)
{
this = base //I know that you can create a reference to the parent class
//by casting this pointer to a Base pointer, but was wondering
//if you can do this the other way around.
printf("%d\n",Base::data);
}
int main()
{
Base* base1 = new Base(5);
Base* base2 = new Base(3);
Child one();
one.run(base1);
delete base1;
delete base2;
base1=0;
base2=0;
return 0;
}
因此,如果此编译(这不)会outputt像5,如果我改变运行参数传递给BASE2它应打印像3.这是可能?谢谢!
实际上,* this = * base会给你一个编译器错误,因为没有Child :: operator =(const Base& )定义。你可以做的static_cast (B)= C ;,这将导致基地::运算符=被调用。无论是否有虚拟功能,这总是很好定义的。 –
2012-07-28 21:22:31
我很好奇,为什么你不鼓励这种类型的任务* this = * base?我得到了编译器错误,但我只是铸造了左值作为基本指针,它工作正常。我想我可以创建一个方法来复制所有的数据或重载赋值运算符,但是我的父类有很多数据,而且非常麻烦。 – 2012-07-28 21:23:02
请把'*此= * base'作为概念性的东西,而不是确切的代码。 – 2012-07-28 23:20:38