什么是 "Expression must have class type"
What is "Expression must have class type"
我在作为对象成员的指针上使用了 std::malloc()。在一个方法中,它抛出了一个错误。
[...]
class SomeClass
{
public:
void method()
{
this.ptr = std::malloc(4);
}
int* ptr;
}
[...]
它抛出一个错误说:
Error: Expression must have class type
我的程序有什么问题?
this.ptr
无效!
this
是一个指针,成员必须用指针运算符访问:
this->ptr = static_cast<int *>(std::malloc(4));
你至少有两个问题:
首先,它应该是 this->ptr
而不是点。
其次,你必须将malloc()
的结果强制转换为你想要的指针类型。例如,this->ptr = static_cast<int *>(malloc(4));
您的代码还有一些其他问题。
您必须 free()
您分配的指针。如果你 malloc
它,你也必须 free
它在某个地方。
您假设 int
的大小为四个字节。这是不正确的。你应该使用 sizeof(int)
。或者至少添加一个 static_assert(sizeof(int) == 4);
如果你必须假设它。
如果您使用 new
分配内存(而不是 malloc
),如下所示:this->ptr = new int;
,您可以同时解决上述两个问题。您不需要强制转换返回的指针,也不会假设 int 的大小始终为 4。
如果你使用new
,不要忘记delete
指针(而不是free
。)
始终将您的指针初始化为 nullptr
,并记得在 freeing/deleting 之后将它们设置为 nullptr
。这可以帮助您避免一些常见的无提示错误。
从风格上讲,您可以避免使用原始指针,而是使用 std::unique_ptr<int>
之类的东西。但这取决于你。
什么奇怪的编译器给出这样的错误信息?
它抱怨 this.ptr
表达式中点运算符的左侧。点运算符假定左侧应该是 class 类型,而 this
是指向 class 类型的指针。你必须使用 ->
.
其次,mallocreturnsvoid*
,你要转换一下。避免麻烦并使用 new int
除非你真的必须使用 malloc。
C++ 不是 Java。你需要 this->
而不是 this.
.
尽管在您的情况下您可以简单地写 ptr = (int*)std::malloc(4)
因为 this->
是隐含的。
更好的是,写 ptr = new int;
因为这样你就不会对 sizeof(int)
做出假设。不要忘记你在某处也需要一个 delete int;
并且你需要担心赋值运算符、复制构造函数和析构函数。
更好的方法是 std::unique_ptr<int>
或 std::shared_ptr<int>
作为 ptr
类型,因此您无需担心 delete
.
如果要求允许,使用 int
作为成员类型可能更好。
可能是因为 this
是一个指针并尝试使用 .
访问它。
此外 malloc returns a void*
所以你必须投
试试这样写:
this->ptr = static_cast<int *>(std::malloc(4));
我在作为对象成员的指针上使用了 std::malloc()。在一个方法中,它抛出了一个错误。
[...]
class SomeClass
{
public:
void method()
{
this.ptr = std::malloc(4);
}
int* ptr;
}
[...]
它抛出一个错误说:
Error: Expression must have class type
我的程序有什么问题?
this.ptr
无效!
this
是一个指针,成员必须用指针运算符访问:
this->ptr = static_cast<int *>(std::malloc(4));
你至少有两个问题:
首先,它应该是 this->ptr
而不是点。
其次,你必须将malloc()
的结果强制转换为你想要的指针类型。例如,this->ptr = static_cast<int *>(malloc(4));
您的代码还有一些其他问题。
您必须
free()
您分配的指针。如果你malloc
它,你也必须free
它在某个地方。您假设
int
的大小为四个字节。这是不正确的。你应该使用sizeof(int)
。或者至少添加一个static_assert(sizeof(int) == 4);
如果你必须假设它。如果您使用
new
分配内存(而不是malloc
),如下所示:this->ptr = new int;
,您可以同时解决上述两个问题。您不需要强制转换返回的指针,也不会假设 int 的大小始终为 4。如果你使用
new
,不要忘记delete
指针(而不是free
。)始终将您的指针初始化为
nullptr
,并记得在 freeing/deleting 之后将它们设置为nullptr
。这可以帮助您避免一些常见的无提示错误。
从风格上讲,您可以避免使用原始指针,而是使用 std::unique_ptr<int>
之类的东西。但这取决于你。
什么奇怪的编译器给出这样的错误信息?
它抱怨 this.ptr
表达式中点运算符的左侧。点运算符假定左侧应该是 class 类型,而 this
是指向 class 类型的指针。你必须使用 ->
.
其次,mallocreturnsvoid*
,你要转换一下。避免麻烦并使用 new int
除非你真的必须使用 malloc。
C++ 不是 Java。你需要 this->
而不是 this.
.
尽管在您的情况下您可以简单地写 ptr = (int*)std::malloc(4)
因为 this->
是隐含的。
更好的是,写 ptr = new int;
因为这样你就不会对 sizeof(int)
做出假设。不要忘记你在某处也需要一个 delete int;
并且你需要担心赋值运算符、复制构造函数和析构函数。
更好的方法是 std::unique_ptr<int>
或 std::shared_ptr<int>
作为 ptr
类型,因此您无需担心 delete
.
如果要求允许,使用 int
作为成员类型可能更好。
可能是因为 this
是一个指针并尝试使用 .
访问它。
此外 malloc returns a void*
所以你必须投
试试这样写:
this->ptr = static_cast<int *>(std::malloc(4));