gpt4 book ai didi

c++ - 基类静态引用数据成员上 C++ 对象切片行为的奇怪案例

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:01 24 4
gpt4 key购买 nike

我正在经历一个奇怪的对象切片案例。我正在从事需要单例类的项目,因此我的基类和派生类都是单例。以下示例案例描述了我的情况。

这是我的基类

// Base.h
class Base
{
public:

static Base& base;

virtual void doSomething(){ cout<<"Base Do Something"<<endl; }

protected:

Base();
virtual ~Base();
static Base& getBaseInstance();

private:
};

//Base.cpp
Base::Base()
{
//ctor
}

Base::~Base()
{
//dtor
}

Base& Base::getBaseInstance()
{
static Base object;
return object;
}
Base& Base::base=Base::getBaseInstance();

这是我的派生类

class Derived: public Base
{
public:

static Derived& derived;
virtual void doSomething(){ cout<<"Derive Do Something"<<endl; }

static Derived& getDerivedInstance();
protected:
Derived();
virtual ~Derived();

private:
};

Derived::Derived()
{
//ctor
}

Derived::~Derived()
{
//dtor
}

Derived& Derived::derived=Derived::getDerivedInstance();

Derived& Derived::getDerivedInstance()
{
static Derived object;
return object;
}

最后这是我的主要功能

int main()
{
cout << "Hello world!" << endl;
Base::base.doSomething();
Derived::derived.doSomething();

Base::base=Derived::derived;

Base::base.doSomething();

Base::base=Derived::getDerivedInstance();

Base::base.doSomething();

Base& r = Derived::derived;

r.doSomething();

Base::base=Derived::getDerivedInstance();
Base::base.doSomething();
return 0;
}

我得到以下输出

Hello world!
Base Do Something
Derive Do Something
Base Do Something
Base Do Something
Derive Do Something
Base Do Something

所以我的问题是,既然对象切片不应该对引用起作用,那为什么我不能覆盖 Base::base 引用我创建为 Base 类的静态数据成员与 Derived 对象?虽然这在 Base& r = Derived::derived;

上运行良好

我的意思是,当我调用 do something with r.doSomething() 时,我得到派生类的 doSomething。但是

却不是这样
    Base::base=Derived::derived;    
Base::base.doSomething();

    Base::base=Derived::getDerivedInstance();    
Base::base.doSomething();

任何形式的澄清将不胜感激。谢谢。

最佳答案

当你做的时候

Base::base=Derived::derived;

您没有设置基引用来引用派生类。这是赋值运算符,它所做的只是将 derivedBase 部分赋给 base

base 仍然是 Base 类型,并且永远不会更改,因为引用只能初始化一次,您可以使用

Base& Base::base=Base::getBaseInstance();

如果您想要这种重新分配行为,您将需要使用指针类型。

关于c++ - 基类静态引用数据成员上 C++ 对象切片行为的奇怪案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38530829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com