我有一个显式函数,它引用了类的基类型。传递它的正确方法是什么?
我目前正在进行静态演员:
#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)
,但这似乎有些过时了。我觉得我只是忽略了一个简单的方法来做到这一点。感谢。
答案 0 :(得分:5)
使用此:
static_cast<Base&>(D)
或者这个:
static_cast<const Base&>(D)