我在该网站上阅读过许多类似的问题,但没有任何内容能回答我正在尝试做的事情。
public class base {
public:
base(){
//Default Constructor
}
base( int num ){
// use num to create base
}
base& operator=( base&& _data ){
// do move assignment stuff
}
};
public class derived : public base {
public:
derived() : base() {
int num1;
//Do some stuff
// Now I want to assign the base of this class with a new base
base::operator=( Base( num1 ) );
}
};
我想在派生类的构造过程中对基类调用移动赋值(或只是常规赋值)。这样,派生类可以在创建其基类之前解析一些信息。这似乎行不通。有人有什么想法吗?
最佳答案
请记住,基类在进入构造函数体之前被初始化。因此,使用您的方法,您首先初始化 base
,然后通过赋值覆盖它。那可不好。
使用委托(delegate)构造函数和私有(private)辅助函数:
class derived : public base {
private:
static int help () { /* Do some stuff */ }
// private constructor to be called with the helper values
derived (int i) : base (i) { }
public:
derived() : derived (help ()) { }
};
当然,在这种情况下,您可以通过以下方式定义您的构造函数
derived () : base (help ()) { }
然而,如果您必须为基类构造函数计算多个参数值,则上述委托(delegate)构造函数方法会变得很有用:
class base {
public:
base (int i, double d);
};
class derived : public base {
private:
struct BaseParams { int i; double d; };
static BaseParams help () {
BaseParams p;
/* Do some stuff and set p.i and p.d */;
return p;
}
// private constructor to be called with the helper values
derived (BaseParams const & p) : base (p.i, p.d) { }
public:
derived() : derived (help ()) { }
};
如果你真的想构造一个 base
对象并将其移动进去,请使用 base 的移动构造函数:
class base {
public:
base (int i, double d);
base (base &&);
};
class derived : public base {
private:
static base help () {
/* Do some stuff and finally construct a base object */;
return base { /* calculated parameters for constructor of base */ };
}
// private constructor to be called with a base object to move from
derived (base && b) : base (std::move (b)) { }
public:
derived() : derived (help ()) { }
// or simply derived () : base (help ()) { }
};
关于c++ - C++运算符的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32212116/