[英]C++ derived class and base copy constructor as pointer
I have a base class aaa
and two derived classes bbb
and ccc
.我有一个基础 class
aaa
和两个派生类bbb
和ccc
。
Is it possible to declare the base class first and then reference it to its derived classes, to make them share the same reference of it?是否可以先声明基础 class 然后将其引用到其派生类,以使它们共享相同的引用?
To show what I mean I wrote this small code:为了说明我的意思,我写了这个小代码:
#include <iostream>
#include <functional>
#include <memory>
class aaa
{
protected:
int a;
public:
aaa(int _a)
{
a = _a;
}
aaa(aaa &_aaa) = default;
aaa(aaa &&_aaa) = default;
int get_a(void)
{
return a;
}
void set_a(int _a)
{
a = _a;
}
int *get_a_addr(void)
{
return &a;
}
};
class bbb : public aaa
{
public:
bbb(aaa &_aaa) : aaa(_aaa)
{
;
}
bbb(aaa &&_aaa) : aaa(_aaa)
{
;
}
};
class ccc : public aaa
{
public:
ccc(aaa &_aaa) : aaa(_aaa)
{
;
}
ccc(aaa &&_aaa) : aaa(_aaa)
{
;
}
};
int main(void)
{
aaa a(10);
bbb b(std::ref(a));
ccc c(std::ref(a));
std::cout << "address of a" << std::endl;
std::cout << a.get_a_addr() << std::endl;
std::cout << b.get_a_addr() << std::endl;
std::cout << c.get_a_addr() << std::endl;
return 0;
}
But b
and c
clearly don't have access to the same memory area of a::a
.但是
b
和c
显然无法访问a::a
的相同 memory 区域。
As far as I know the only way to accomplish this is using nested classes.据我所知,实现这一点的唯一方法是使用嵌套类。 Isn't possible the way I am trying to?
不可能像我尝试的那样吗?
All three objects have a different instance of the a member.所有三个对象都有不同的 a 成员实例。 And since you return the address of the ˋaˋ member in ˋget_a_addressˋ and not its content, the return value differs for each object.
而且由于您在ˋget_a_addressˋ中返回ˋaˋ成员的地址而不是其内容,因此每个object的返回值不同。 I assume you want to return the same value (the content of the ˋaˋ object) for all these calls.
我假设您希望为所有这些调用返回相同的值(ˋaˋ 对象的内容)。
No, each base class subobject is independent of all other subobjects.不,每个基础 class 子对象都独立于所有其他子对象。 What you can do is have a fake base class, whose only job is to reference the real thing.
你能做的是有一个假基地 class,它唯一的工作就是参考真实的东西。
class realA
{
void foo() { ... }
void bar() { ... }
};
class a
{
...
void foo() { impl->foo(); }
void bar() { impl->bar(); }
std::shared_ptr<realA> impl;
};
a
behaves just like realA
because it has all the same methods as realA
, doing the same thing. a
行为与realA
一样,因为它具有与realA
相同的方法,做同样的事情。
Your b
and c
still have separate a
subobjects, but now they may share the same realA
object, which is the class that does the real work.您的
b
和c
仍然有单独a
子对象,但现在它们可能共享相同的realA
object,即真正起作用的 class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.