【发布时间】:2017-12-07 18:56:59
【问题描述】:
我有这样的代码:
class Human
{
protected:
int age;
std::string sex;
public:
virtual void speak() = 0;
};
class Child:public Human
{
public:
void speak(){std::cout << "I am Child\n";}
};
class Man:public Human
{
public:
void speak(){std::cout << "I am Man\n";}
};
class Woman:public Human
{
public:
void speak(){std::cout << "I am Woman\n";}
};
(don't know, std::shared_ptr<Human> maybe?) operator*(std::shared_ptr<Child> &b, int x)
{
b->setAge(b->getAge()+x);
if(b->getAge()>18 && b->getSex()=="Man")
{
return (i want b to become std::shared_ptr<Man>)
}
if(b->getAge()>18 && b->getSex()=="Woman")
{
return (here I want b to become std::shared_ptr<Woman>);
}
return;
}
int main(){
auto x = std::make_shared<Child>;
x*19;
}
我知道这看起来很奇怪,但这是我能想到的最简单的情况,无需写下我在 rn 上苦苦挣扎的所有代码。有人可以解释一下,应该重载什么类型以及如何更改 shared_ptr 类型,知道它们是从同一个父级派生的吗?
【问题讨论】:
-
您是在问如何为
shared_ptr本身定义运算符重载吗? -
无论你放什么类型,这个特定的代码都不会构建。用一个简短的段落描述您希望达到的目标怎么样?
-
@OliverCharlesworth 不,只是想知道是否可以将 ptr 类型从 b 更改为 c 如果它们都派生自同一个类,以及方法是否可以返回 ptr 或 ptr
,取决于 if 语句 -
我的意思是,
x*8无法编译 -x是shared_ptr。 -
@OliverCharlesworth -
x成为shared_ptr本身并不是一个障碍。将操作符参数类型从B更改为shared_ptr<B>完全没问题。
标签: c++ oop inheritance std shared-ptr