在c++中期望主表达式在token之前

expecting primary expression before token in c++

本文关键字:token 之前 表达式 期望 c++      更新时间:2023-10-16

问题是:

在console.cpp

void Console::PrintMedicine(Medicine* m){
    int ID = Medicine.getID(); //here i get the error expecting primary expression before "." token, it doesn't work with -> either
    cout<<"The Medicine's ID is: ";
    cin>>ID;
}

类药物:

私人:

private:
    int ID;
    std::string nume;
    double concentratie;
    int cantitate;

什么是公共

public:
    Medicine();  //implcit constructor
    Medicine(int ID, std::string nume, double concentratie, int cantitate);//constructor with parameteres
    ~Medicine(); //destructor

//getID函数

        const int& Medicine::getID() const{
    return this->ID;
}

//getName函数

const std::string& Medicine::getName() const{
    return this->nume;
}

//getConcentration函数

const double& Medicine::getConcentration() const{ 
    return this->concentratie;
}

//getQuantity函数

const int& Medicine::getQuantity() const{
    return this->cantitate;
}

表达式Medicine.getID()不正确。Medicine的名称,不能使用点运算符访问其成员。首先,你需要一个Medicine实例,你想访问它的成员;其次,如果您有一个指向该实例的指针,则需要使用箭头操作符(operator ->)。

因此,它应该是:

void Console::PrintMedicine(Medicine* m){
    int ID = m->getID();
//           ^^^
// ...
}