【问题标题】:How to call a constructor for a class inside another class?如何在另一个类中调用一个类的构造函数?
【发布时间】:2018-05-15 17:59:16
【问题描述】:

我有一个类first,我想在其中有另一个元素,它的类型是另一个类。像这样的:

class first{

private:

    second secondAvl;
public:

    first():second(-1){}  // i get erroe here
} 

class second: public Tree{

private:

public:
 second(int key) :Tree(NULL,key1){} // here it worked to call contructor for tree
}

我的问题是,当我尝试在类第一个构造函数中调用第二个构造函数时,出现此错误:

没有匹配的函数调用'second::second()'

任何帮助我做错了什么?因为当我在第二个类中调用树的构造函数时我做了同样的事情并且效果很好。

【问题讨论】:

  • 您需要命名成员,而不是成员的类型。 first() : secondAvl(-1) {} 考虑如果您有两个 second 成员会发生什么。只有在调用基类型的构造函数时才能命名类型。请记住,second 必须在用于 first 之前声明。
  • first():second(-1){} 这表示:“当默认构造 first 时,通过调用值为 -1 的构造函数来初始化名为 second 的成员。”您没有名为 second 的成员,因此失败。
  • 提供的代码无法触发报错。

标签: c++ class inheritance


【解决方案1】:

首先,按照定义类的顺序,类secondfirst 中使用时是未知的。您实际上应该收到其他错误消息。 其次,在初始化列表中,您需要通过其名称(即: secondAvl(-1))而不是其类型: second(-1)来寻址要初始化的变量。

请参阅以下工作示例:

class second {

private:

public:
    second(int key) {} // here it worked to call contructor for tree
};


class first{

private:

    second secondAvl;
public:

    first():secondAvl(-1){}  // i get erroe here
};

【讨论】:

    【解决方案2】:

    改为:

    ...
    
    private:
    
        second secondAvl;
    public:
    
        first() : secondAvl(-1)
        { }  
    }
    

    或使用 {}

    进行统一初始化
    ...
    
    private:
    
        second secondAvl;
    public:
    
        first() : secondAvl{-1}
        { }  
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 1970-01-01
      • 2014-08-01
      • 2012-06-22
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多