错误:请求“ ..”中的成员“ ..”属于非类类型
作者:互联网
我有一个带有两个构造函数的类,一个不带参数,而一个带一个参数。
使用接受一个参数的构造函数创建对象的工作符合预期。 但是,如果我使用不带参数的构造函数创建对象,则会出现错误。
例如,如果我编译此代码(使用g ++ 4.0.1)...
<code>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; }
...我收到以下错误:
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 ()()’
为什么会这样,如何使它起作用?
#1楼
只是为了记录。
它实际上不是您的代码的解决方案,但是当错误地访问myPointerToClass
指向的类实例的方法时,我遇到了相同的错误消息。
MyClass* myPointerToClass = new MyClass();
myPointerToClass.aMethodOfThatClass();
哪里
myPointerToClass->aMethodOfThatClass();
显然是正确的。
#2楼
添加到知识库中,我遇到了相同的错误
if(class_iter->num == *int_iter)
即使IDE为我提供了class_iter的正确成员。 显然,问题在于"anything"::iterator
没有名为num
的成员,因此我需要取消引用它。 不能这样工作:
if(*class_iter->num == *int_iter)
...显然。 我最终用以下方法解决了它:
if((*class_iter)->num == *int_iter)
我希望这可以帮助像我一样遇到这个问题的人。
#3楼
我遇到了类似的错误,似乎编译器误解了对不带参数的构造函数的调用。 我通过从变量声明中删除括号来使其工作,在您的代码中如下所示:
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;
}
#4楼
当您不打算使用参数化的构造函数时,不需要括号来实例化类对象。
只需使用Foo foo2;
它会工作。
#5楼
我遇到了一个错误消息,
Foo foo(Bar());
并基本上试图将临时Bar对象传递给Foo构造函数。 原来编译器正在将其翻译成
Foo foo(Bar(*)());
也就是说,名称为foo的函数声明返回一个带参数的Foo -函数指针返回带0个参数的Bar。 当这样传递临时消息时,最好使用Bar{}
而不是Bar()
消除歧义。
#6楼
如果要声明不带参数的新物质(知道对象具有默认参数),请不要编写
type substance1();
但
type substance;
#7楼
当然可以解决此错误,但是当尝试重载赋值operator=
时,我在另一种情况下收到了它。 这是一个有点神秘的IMO(来自g ++ 8.1.1)。
#include <cstdint>
enum DataType
{
DT_INT32,
DT_FLOAT
};
struct PrimitiveData
{
union MyData
{
int32_t i;
float f;
} data;
enum DataType dt;
template<typename T>
void operator=(T data)
{
switch(dt)
{
case DT_INT32:
{
data.i = data;
break;
}
case DT_FLOAT:
{
data.f = data;
break;
}
default:
{
break;
}
}
}
};
int main()
{
struct PrimitiveData pd;
pd.dt = DT_FLOAT;
pd = 3.4f;
return 0;
}
我收到2个“完全相同”的错误
error: request for member ‘i’ [and 'f'] in ‘data’, which is of non-class type ‘float’
( clang
的等效错误是: error: member reference base type 'float' is not a structure or union
)
对于行data.i = data;
和data.f = data;
。 事实证明,编译器混淆了局部变量名称'data'和我的成员变量data
。 当我将其更改为void operator=(T newData)
和data.i = newData;
, data.f = newData;
,错误消失了。
#8楼
Foo foo2();
改成
Foo foo2;
因为编译器认为您得到错误
Foo foo2()
从名称为“ foo2”的函数声明开始,返回类型为“ Foo”。
但是在那种情况下,如果我们更改为Foo foo2
,则编译器可能会显示错误" call of overloaded 'Foo()' is ambiguous"
。
标签:请求,错误,int,..,Foo,data,class,foo2 来源: https://blog.csdn.net/asdfgh0077/article/details/104180117