开发者

Why doesn't this initialize correctly?

I'm trying to initialize a class constructor within another constructor. The GCC raises the error, 'Type 'foo' does not have a call operator.'This psuedo-code should explain my intentions.

class foo {  
    typ开发者_运维问答e arg1, arg2;
    foo (type _arg1, type _arg2) {  
        _arg1=arg1;  
        _arg2=arg2;  
    }  
}

class foo2 {  
    foo member;

    foo2(type _arg1, type _arg2) {  
        member(_arg1, _arg2);  
    }  
}


Two issues:

First, your foo constructor should be public, as stated in Mark's answer.

Second, to initialize the member with its constructor, you should use the following syntax:

foo2(type _arg1, type _arg2) :
   member(_arg1, _arg2)
   { /* code */ }  


Your constructors are not public; by default, everything in a class is private unless you specify otherwise. I'm not sure this explains your exact error message though.


You want the initializer list:

foo2(type _arg1, type _arg2) : member(_arg1,_arg2) { }


You're trying to use member's constructor. You should do that in the initializer list and not in the constructor body, i.e.:

foo2(type _arg1, type _arg2)
    : member(_arg1, _arg2)
{  
}  


The pseudo-code may explain your intention but it doesn't explain your error as it doesn't error in the way you describe:

class foo {  
    type arg1, arg2;
    foo (type _arg1, type _arg2) {  
        _arg1=arg1;  
        _arg2=arg2;  
    }  
}

class foo2 {  
    foo member;

    foo2(type _arg1, type _arg2) {  
        member(_arg1, _arg2);  
    }  
}

Although it does yield helpful diagnostics:

gcc -Wall junk.cc 
junk.cc: In constructor ‘foo2::foo2(int, int)’:
junk.cc:12:32: error: no matching function for call to ‘foo::foo()’
junk.cc:3:5: note: candidates are: foo::foo(int, int)
junk.cc:1:11: note:                 foo::foo(const foo&)
junk.cc:13:28: error: no match for call to ‘(foo) (int&, int&)’
junk.cc: At global scope:
junk.cc:14:5: error: expected unqualified-id at end of input

Which shows that you shouldn't post "sorta like" code here and expect useful answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜