简体   繁体   English

如何在另一个类中调用一个类的构造函数?

[英]How to call a constructor for a class inside another class?

I have a class first in which I want to have another element that its type is another class.first有一个类,其中我想要另一个元素,它的类型是另一个类。 Something like this:像这样的东西:

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
}

My problem is that when I try to call the constructor for second in class first constructor I get this error:我的问题是,当我尝试在类第一个构造函数中调用第二个构造函数时,出现此错误:

no matching function for call to 'second::second()'没有用于调用“second::second()”的匹配函数

Any help what I am doing wrong?任何帮助我做错了什么? Because I did the same thing when I called the constructor for tree in the second class and that worked fine.因为当我在第二个类中调用 tree 的构造函数时我做了同样的事情并且工作正常。

First, in the order you define the classes, class second is not known at the time it is used in first .首先,在你定义类的顺序,类second不以它在使用时已知first You should actually get other error messages.您实际上应该收到其他错误消息。 Second, in the initializer list, you need to address the variable to initialize by its name (ie : secondAvl(-1) ), not by its type : second(-1) .其次,在初始值设定项列表中,您需要按名称(即: secondAvl(-1) )而不是其类型来寻址要初始化的变量: second(-1)

See the following working example:请参阅以下工作示例:

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
};

do instead:改为:

...

private:

    second secondAvl;
public:

    first() : secondAvl(-1)
    { }  
}

or uniform initialization using {}或使用 {} 统一初始化

...

private:

    second secondAvl;
public:

    first() : secondAvl{-1}
    { }  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM