C++ 使用“this”关键字时出现“错误:表达式必须具有指针类型”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13104138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:57:56  来源:igfitidea点击:

"Error: expression must have a pointer type" when using the "this" keyword

c++this

提问by user1779944

So I made a parent class, which i will call Parentthat has a Square*grid member variable. The grid variable is a pointer to a large array of Squares, which contain keymember variables. (Think of this project as a hashtable) The problem is I am making a function in the Parentclass that edits the key variables in the Squarearray, and getting an error. This line of code compiles:

所以我创建了一个父类,我称之为Parent具有Square*网格成员变量。grid 变量是一个指向包含key成员变量的大型 Squares 数组的指针。(将此项目视为哈希表)问题是我在Parent类中创建了一个函数来编辑Square数组中的关键变量,但出现错误。这行代码编译:

this->grid = new Square[row*col];

but this line does not compile:

但这行不编译:

this->grid[i*col + j]->key1 = j;

it underlines thisand says expression must have a pointer type. I was wondering if anyone had ideas to what i may be doing wrong?

它强调this并表示表达式必须具有指针类型。我想知道是否有人对我可能做错了什么有想法?

void Parent::initialize(int row,int col) {
    this->grid = new Square[row*col];
    for(int i = 0; i < row; i++) {
        for(int j = 0;j < col; j++) {
            this->grid[i*col + j]->key1 = j;
            this->grid[i*col + j]->key2 = i;
        }
    }

回答by il_guru

You have to use

你必须使用

this->grid[i*col + j].key1
this->grid[i*col + j].key2

That is because even if it is true that your grid is a pointer, you have allocated in the are pointed by its memory an array of Squareobject. So when you use the [] operator you are obtaining an object of type Squareand not a Square*and for a Squareobject you hve to use the . operatorand not the -> operator.

那是因为即使您的网格确实是一个指针,您也已在其内存指向的Square对象中分配了一个对象数组。因此,当您使用 [] 运算符时,您将获得一个类型Square而不是 a的对象,Square*并且对于一个Square对象,您必须使用. 运算符而不是-> 运算符。

回答by PiotrNycz

I guess this->gridis of type Square*, so this->grid[0]is of type Square&and you must use .(dot) not ->(arrow) to access members from Square&. To use arrow for expression expression must have a pointer type...

我猜this->grid是 type Square*,所以this->grid[0]也是 type Square&,你必须使用.(点)而不是->(箭头)从Square&. 要使用箭头表达式表达式必须有一个指针类型...

this->grid[i*col + j]->key2
//                   ^^: this->grid[i*col + j] is not a pointer 
this->grid[i*col + j].key2
//                   ^ use dot to access key2 and key1 too