gpt4 book ai didi

c++ - 显式传递基类型

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:36 24 4
gpt4 key购买 nike

我有一个显式函数,它引用一个类的基类型。传递它的正确方法是什么?

我目前正在进行静态转换:

#include <iostream>

using namespace std;

struct Base
{
Base() { cout << "Base Constructor" << endl; }
Base(Base const& c) { cout << "Base-Base Constructor" << endl; }
};

struct Derived : public Base
{
Derived() { cout << "Derived Constructor" << endl; }
explicit Derived(Base const& c) { cout << "Derived-Base Constructor" << endl; }
Derived(Derived const& c) { cout << "Derived-Derived Constructor" << endl; }
};

int main()
{
Base B;
cout << "\n";
Derived D;
cout << "\n";
Base* test1 = new Derived(D);
cout << "\n";
Base* test3 = new Derived(static_cast<Base>(D));
cout << "\n";
Base* test2 = new Derived(B);
cout << "\n";


return 0;
}

但这会调用基类的复制构造函数。

我可以通过 *static_cast<Base*>(&D) ,但这似乎有点骇人听闻。我觉得我只是忽略了一种简单的方法来做到这一点。谢谢。

最佳答案

使用这个:

static_cast<Base&>(D)

或者这个:

static_cast<const Base&>(D)

关于c++ - 显式传递基类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25330714/

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