繁体   English   中英

访问 class 内部的指针

[英]Accessing pointers inside class

我试图在 class 中使用指针变量,但它给了我一个错误

Car.cpp:15:16: 错误:->* 的右手操作数具有非指针成员类型'int *' return this->*tires;

这是我的程序

主文件

#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;
}

汽车.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

汽车.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;
}

在 Car.cpp 上,方法 Car::getTires 存在似乎已经合乎逻辑的错误,我尝试使用 this->tires 或 this->(*tires) 但它仍然给了我错误。

整个变量称为this->tiresthis指的是当前的 object ,而tires指的是成员本身。

因此,您需要取消引用变量而不是“它的一部分”。

要么使用:

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

哪个有效,因为this是编译器自动暗示的,或者

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

return *this->tires; 也应该起作用,因为运算符优先级将->放在*之前(这意味着它在尝试取消引用变量之前首先评估 this )。 https://en.cppreference.com/w/cpp/language/operator_precedence

这是一个语法错误。 ->*.*如果指向完全不同的动物的成员(更多关于cppreferences

在这里,您只有一个恰好是指针的成员。 您可以简单地使用*tires*this->tires取消引用它。

暂无
暂无

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

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