首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用友元类重载构造函数

用友元类重载构造函数
EN

Stack Overflow用户
提问于 2011-04-12 21:13:03
回答 1查看 1.2K关注 0票数 3

我有一个使用静态列表(本例中为firstFriend)或动态列表(本例中为secondFriend)进行初始化的类。我不想在示例中编写列表功能,因为它并不重要。关键问题是firstFriend和secondFriend是好朋友。类"target“的构造函数的代码是相同的:如果我重载这些构造函数,我就会复制完全相同的代码。我不能给构造器设置模板,因为它不工作。

下面是示例(注意: firstFriend和secondFriend可能看起来是一样的,但在实际代码中却不一样,这只是一个大大简化的模型,它们的属性和功能之间的差异在“目标”类构造函数中没有任何区别,因为公共接口的部分是从两个完全相同的类中使用的):

代码语言:javascript
复制
template <class T>
class firstFriend 
{
    public:
    firstFriend() {};

    firstFriend(const T& t) {};

    private:
    T tAttribute; 
};


template <class T>
class secondFriend 
{
    public:

    secondFriend() {};

    secondFriend(T t) : tAttribute(t) {};

    friend class firstFriend<T>;

    private:

        T tAttribute;
};

class target
{
    public:
    target(const firstFriend<int>&) 
    {
        // Some nice initialization of the TargetData.
    }
    target(const secondFriend<int>&)
    {
        // Exactly the same initialization as above. 
        // To the single character. 
    }; 
    private:
    firstFriend<int> TargetData;
};

问:如何在不编写(复制/粘贴)相同代码的情况下重载构造函数?我尝试过将构造器模板化,但它不起作用。也许是隐式强制转换?最有效的方法是什么( firstFriend和secondFriend是巨大的数据列表)。提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-12 21:18:41

如果两个构造函数具有完全相同的代码,则可以编写构造函数模板,如下所示:

代码语言:javascript
复制
template<class FriendType >
target(const FriendType &) 
{
    // Some nice initialization of the TargetData.
}

如果有一点不同,但大部分代码是相同的,那么您可以编写一个init模板函数,并从两个构造函数中调用它,如下所示:

代码语言:javascript
复制
  target(const firstFriend<int>& arg) 
  {
     init(arg);
     //other code
  }
  target(const secondFriend<int>& arg)
  {
     init(arg);
     //other code
  }
private:
  template<class FriendType >
  void init(const FriendType &) 
  {
     //common code
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5635750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档