简体   繁体   English

访问 class 内部的指针

[英]Accessing pointers inside class

i am trying to use a pointer variable in a class but instead it gave me an error我试图在 class 中使用指针变量,但它给了我一个错误

Car.cpp:15:16: error: right hand operand to ->* has non-pointer-to-member type 'int *' return this->*tires; Car.cpp:15:16: 错误:->* 的右手操作数具有非指针成员类型'int *' return this->*tires;

here is my program这是我的程序

main.cpp主文件

#include <iostream>
#include "Car.h"

using namespace std;

int main(){
    int x = 5;
    Car honda("honda", &x);
    
    cout << honda.getBrand() << " " << honda.getTires() << endl;
    x = 6;
    cout << honda.getBrand() << " " << honda.getTires() << endl;

    return 0;
}

Car.h汽车.h

#ifndef CAR_H
#define CAR_H

#include <string>

using namespace std;

class Car {
    private:
        string brand;
        int *tires;
    public:
        Car(string brand, int *tires);
        string getBrand();
        int getTires();
};

#endif

Car.cpp汽车.cpp

#include "Car.h"

using namespace std;

Car::Car(string brand, int *tires){
    this->brand = brand;
    this->tires = tires;
}

string Car::getBrand(){
    return this->brand;
}

int Car::getTires(){
    return this->*tires;
}

on Car.cpp the method Car::getTires lies the error which seems to already be logical, i tried to use this->tires or this->(*tires) but it still gave me error.在 Car.cpp 上,方法 Car::getTires 存在似乎已经合乎逻辑的错误,我尝试使用 this->tires 或 this->(*tires) 但它仍然给了我错误。

The entire variable is called this->tires , the this referring to the current object and the tires referring to the member itself.整个变量称为this->tiresthis指的是当前的 object ,而tires指的是成员本身。

As such, you need to dereference the variable and not 'a part of it`.因此,您需要取消引用变量而不是“它的一部分”。

Either use:要么使用:

int Car::getTires(){
    return *tires;
}

which works, because the this is implied automatically by the compiler or哪个有效,因为this是编译器自动暗示的,或者

int Car::getTires(){
    return *(this->tires);
}

return *this->tires; should also work, because the operator precedence puts the -> before the * (meaning it first evaluates the this prior to trying dereferencing the variable).也应该起作用,因为运算符优先级将->放在*之前(这意味着它在尝试取消引用变量之前首先评估 this )。 ( https://en.cppreference.com/w/cpp/language/operator_precedence ) https://en.cppreference.com/w/cpp/language/operator_precedence

This is a syntax error.这是一个语法错误。 ->* or .* if for pointer to members which are quite different animals (more on cppreferences ) ->*.*如果指向完全不同的动物的成员(更多关于cppreferences

Here you just have a member which happens to be a pointer.在这里,您只有一个恰好是指针的成员。 You can simply dereference it with *tires or *this->tires .您可以简单地使用*tires*this->tires取消引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM