如果我将(指向A类的指针施放为(指向其子类B)在C 中)会发生什么
what happens if I cast (a pointer to class A) to (a pointer to its subclass B) in c++
a具有静态函数a :: create()创建a的实例,进行一些初始化并返回指针。我想创建一个A子类,并具有类似的Create()func:
class B : public A {
public:
static B* create();
int val;
//...
}
在此B :: create()函数中,我必须执行以下操作:
B* B::create() {
auto b = (B*)A::create();
b -> val = 0;
//...
return b;
}
这是正确的方法吗?演员之后会发生什么?
随访:A具有受保护/私有构造函数,我应该如何编写B :: create()或B的构造函数?我确实希望从a继承的var具有与a :: create()创建的值相同的值。
除非A::create()
将指针返回到B
对象,否则演员将不会做任何明智的事情。如果A::create()
将指针返回到不是B
的对象的指针,则您的行为不确定。
在C 中,您使用构造函数处理对象的初始化:基本类的初始化是继承的,并且每个派生都可以执行任何自定义初始化的操作。您的B::create()
只会返回适当构造的对象:
B::B()
: A() // initialize base
, val(0) {
// other initialization
}
B* B::create() { return new B(); }
您可以使B类成为一个这样的朋友
class A {
public:
static A* createA();
int varA;
private:
friend class B; // Make B a friend so that B can use private constructor of A
A()
{
cout << "In A constructor" << endl;
varA = 5; // Initialize members of A here
}
};
A* A::createA()
{
return new A;
}
class B : public A {
public:
static B* createB();
int varB;
private:
B()
{
cout << "In B constructor" << endl;
varB = -5; // Initialize members of B here
}
};
B* B::createB()
{
return new B;
}
int main()
{
cout << "Create A" << endl;
A* x=A::createA();
cout << "x->varA is " << x->varA << endl;
cout << endl;
cout << "Create B" << endl;
B* y=B::createB();
cout << "y->varA is " << y->varA << endl;
cout << "y->varB is " << y->varB << endl;
cout << endl;
delete x;
delete y;
}
制作新的B时,将自动调用A的构造函数,A的成员将被初始化。
输出是:
Create A
In A constructor
x->varA is 5
Create B
In A constructor
In B constructor
y->varA is 5
y->varB is -5
另一种方法是使受保护的构造函数而不是私人。
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 必须具有泛型接口的函数,但必须根据传递的子类(不知道它们是什么!)以不同的行为 - C++
- 子类的构造函数后跟冒号后的基类构造函数是什么意思?
- 我构造子类对象的方式有什么问题?
- 在C++中,继承超类的正确方法是什么,以便它们的子类在超级类和子类中没有重复的属性?
- 如果我将(指向A类的指针施放为(指向其子类B)在C 中)会发生什么
- C++ 在超类构造函数中运行依赖于子类覆盖的大量变量的代码的正确方法是什么?
- C++中包含父类对象的子类有什么问题(如果有的话)
- 以错误的方式调用子类中的函数的最佳方法是什么
- c++:对于多重继承类的子类中的重复成员字段,什么是好的重构
- 视觉 C++当我们在基类中使函数成为纯虚拟时,那么在子类中再次使相同的函数虚拟的必要性是什么
- 虚函数的参数未在所有子类中使用;有什么更好的设计方法吗?
- C++:使用超类和子类,简单计算面积的值返回3.47668e-310,无论我输入什么来计算
- 我尝试对 CButton 进行子类化有什么问题?
- 子类继承的非公共虚函数会发生什么情况
- 堆栈和子类之间的正确UML关系是什么
- 继承子类时的默认保护级别是什么