简体   繁体   English

如何在C ++中的同一类的构造函数中调用重载的构造函数?

[英]How to call an overloaded constructor within a constructor of the same class in c++?

I have two very related problems; 我有两个非常相关的问题; first, to call a overloaded constructor within a same class and second, to reinitialize the calling object with load_from_file() function. 首先,在同一类中调用重载的构造函数,其次,使用load_from_file()函数重新初始化调用对象。 Here is an example: 这是一个例子:

class FooA: FooB
{
  FooA();
  FooA(myDataType distribution):FooB(distribution)
  FooA(myClasstype objectA):FooA(objectA.get_distribution){} // suppose objectA has a method get_distribution(). 
..
...

} 

It gives an error: 它给出了一个错误:

illegal member initialization 非法成员初始化

Second problem: 第二个问题:

class FooA: FooB
{
  FooA();
  FooA(myDataType distribution):FooB(distribution)

void load_from_file(string file_name){
         // i have another library function to load from file
         JointDistribution jd = load_from_file(file_name);

        // now i want to re-configure the current object
        *this = FooA(jd);
}

FooA* fa = new FooA(); FooA * fa =新的FooA();

fa.load_from_file("file_name"); fa.load_from_file(“ file_name”);

There are different file formats, so it is difficult to put them as a constructor. 文件格式不同,因此很难将其用作构造函数。

第一个问题-如果objectA.get_distribution是一个方法,则应该在那里调用一个方法:FooB(objectA.get_distribution())

here: 这里:

    class FooA: FooB
    {
      FooA();
      FooA(myDataType distribution):FooB(distribution)

       void load_from_file(string file_name){
       }
    };

function load_from_file is private so you can't call it like you have written: 函数load_from_file是私有的,因此您不能像编写时那样调用它:

FooA* fa = new FooA();
fa.load_from_file("file_name");

constructors are private also... (though sometimes we want them to be private, but I assume here it is not the case xD] 构造函数也是私有的(尽管有时我们希望它们是私有的,但我认为这里不是xD的情况)

you can call constructor from constructor: 您可以从构造函数调用构造函数:

class CComplex{
public:
    CComplex(int real1,int image1)
    {
        real=real1;
        image=image1;
        const char& x='x';
        CComplex(1,2,3);
    }
    CComplex():real(0),image(0){}
    CComplex(const CComplex &c)
    {
        real=c.real;
        image=c.image;
    }
    CComplex(int i1, int i2, int i3){cout<<"\n123!";}
public:


    int real,image;
};

For your first question, there is no constructor delegation prior to c++11, while the syntax you have used is correct for c++11. 对于第一个问题,c ++ 11之前没有构造函数委托,而您使用的语法对于c ++ 11是正确的。 Just make sure you've enabled c++11 compilation and it should work fine. 只要确保已启用c ++ 11编译,它就可以正常工作。 If you can't use C++11 you're going to have to duplicate some code. 如果您不能使用C ++ 11,则必须重复一些代码。

I can't understand if/what your second question is (regarding reload). 我不明白您的第二个问题是否(关于重新加载)。

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

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