如何在C ++ 03中伪造构造函数继承? [英] How can I fake constructor inheritance in C++03?

查看:148
本文介绍了如何在C ++ 03中伪造构造函数继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,你不能继承C ++中的构造函数。但是在某些情况下,它可能需要看起来像你可以实例化继承的类,就像你实例化它们的基地一样:

  struct Base {
int i;
int const j;
Base(int i,int j):i(i),j(j){}
};

//选项1)
struct Derived1:Base {
Derived1(int i,int j):Base(i,j){}
}
Base * baseFactory(){
return new Derived1(42,77);
}

//选项2)
struct Derived2:Base {
};
Base * baseFactory(){
Base * b = new Derived2();
b-> i = 42;
b-> j = 47; //破了!
//替代方法可以实现Base :: operator =
return b;
}

请注意,派生类可以是默认构造的,基本类。



选项1是通常做的,我想,但你是打字的代码,没有表示任何新的。选项2打破 const 正确性(并防止您使用引用作为成员)。因为一切都必须是可分配的。



编辑:C ++ 11是伟大的,但不幸的是,我需要一个C ++ 03解决方案。

/ p>

解决方案

有一种替代方法:

  // option 3)
struct Derived3:Base {
Derived3(const Base& b):Base(b){}
};
Base * baseFactory3(){
return new Derived3(Base(42,47));
}

这可能不是一个好主意,如果构建一个完整的Base对象是昂贵的,需要外部资源。在这种情况下,您可以创建一个轻量级对象,其中携带Base的构造函数参数,因此,您可以使用多个Base构造函数,而不是多个BaseArguments构造函数,以及一个包含BaseArguments的Base构造函数。然而,我认为在大多数情况下,很多人不会考虑这种良好的风格。


As far as I know, you cannot inherit constructors in C++. But there are situations, where it might be required that it looks like you can instantiate inherited classes the same way you instantiate their base:

struct Base {
  int i;
  int const j;
  Base(int i, int j) : i(i), j(j) {}
};

// option 1)
struct Derived1 : Base {
  Derived1(int i, int j) : Base(i,j) {}
};
Base* baseFactory() {
  return new Derived1(42,47);
}

// option 2)
struct Derived2 : Base {
};
Base* baseFactory() {
  Base* b = new Derived2();
  b->i = 42;
  b->j = 47; // broken!
  // alternative could be to implement Base::operator=
  return b;
}

Note that the derived classes could be default constructed if it weren't for their base class(es).

Option 1 is what is usually done, I think, but you are typing code without expressing anything new. Option 2 breaks const correctness (and prevents you from using references as members) because everything must be assignable.

Is there a nice way around this?

Edit: C++11 is great, but unfortunately I need a C++03 solution.

解决方案

There is an alternative approach:

// option 3)
struct Derived3 : Base {
  Derived3(const Base &b) : Base(b) {}
};
Base* baseFactory3() {
    return new Derived3(Base(42,47));
}

This may not be a good idea if constructing a full Base object is expensive or requires external resources. In that case you could create a light-weight object that carries constructor arguments for Base, so that instead of multiple Base constructors you have multiple BaseArguments constructors, and one Base constructor that takes in BaseArguments. However I don't think many people would consider that good style in most circumstances.

这篇关于如何在C ++ 03中伪造构造函数继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆