[英]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->tires
, this
指的是當前的 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.