简体   繁体   中英

Accessing pointers inside class

i am trying to use a pointer variable in a class but instead it gave me an error

Car.cpp:15:16: error: right hand operand to ->* has non-pointer-to-member type '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

#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

#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.

The entire variable is called this->tires , the this referring to the current object and the tires referring to the member itself.

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

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). ( 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 )

Here you just have a member which happens to be a pointer. You can simply dereference it with *tires or *this->tires .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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