我有一个带有两个构造函数的类,一个不带参数,另一个带一个参数.
使用带有一个参数的构造函数创建对象可以按预期工作.但是,如果我使用不带参数的构造函数创建对象,我会收到错误.
例如,如果我编译此代码(使用g ++ 4.0.1)...
class Foo
{
public:
Foo() {};
Foo(int a) {};
void bar() {};
};
int main()
{
// this works...
Foo foo1(1);
foo1.bar();
// this does not...
Foo foo2();
foo2.bar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
...我收到以下错误:
nonclass.cpp: In function ‘int main(int, const char**)’:
nonclass.cpp:17: error: request for member ‘bar’ in ‘foo2’, which is of non-class type ‘Foo ()()’
Run Code Online (Sandbox Code Playgroud)
为什么这样,我如何使它工作?
Myk*_*yev 628
Foo foo2();
Run Code Online (Sandbox Code Playgroud)
改成
Foo foo2;
Run Code Online (Sandbox Code Playgroud)
你得到错误,因为编译器认为
Foo foo2()
Run Code Online (Sandbox Code Playgroud)
具有名称'foo2'的函数声明和返回类型'Foo'.
但在这种情况下,如果我们改为Foo foo2,编译器可能会显示错误 " call of overloaded ‘Foo()’ is ambiguous".
ezd*_*ena 39
仅供记录..
它实际上不是您的代码的解决方案,但是当错误地访问指向的类实例的方法时,我有相同的错误消息myPointerToClass,例如
MyClass* myPointerToClass = new MyClass();
myPointerToClass.aMethodOfThatClass();
Run Code Online (Sandbox Code Playgroud)
哪里
myPointerToClass->aMethodOfThatClass();
Run Code Online (Sandbox Code Playgroud)
显然是正确的.
Mat*_*att 11
添加到知识库,我得到了相同的错误
if(class_iter->num == *int_iter)
Run Code Online (Sandbox Code Playgroud)
尽管IDE为我提供了class_iter的正确成员.显然,问题是"anything"::iterator没有一个成员被叫,num所以我需要取消引用它.这不是这样的:
if(*class_iter->num == *int_iter)
Run Code Online (Sandbox Code Playgroud)
...很明显.我最终解决了这个问题:
if((*class_iter)->num == *int_iter)
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助那些以我的方式遇到这个问题的人.
小智 6
我遇到了类似的错误,似乎编译器误解了对不带参数的构造函数的调用。我通过从变量声明中删除括号来使其工作,在您的代码中如下所示:
class Foo
{
public:
Foo() {};
Foo(int a) {};
void bar() {};
};
int main()
{
// this works...
Foo foo1(1);
foo1.bar();
// this does not...
Foo foo2; // Without "()"
foo2.bar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
406757 次 |
| 最近记录: |