C++ 错误 - 令牌之前的预期主表达式'.'|

C++ Error - expected primary-expression before '.' token|

本文关键字:表达式 错误 令牌 C++      更新时间:2023-10-16

我只想说我还在学习C++所以我从关于类和结构的模块开始,虽然我并不了解所有内容,但我认为我做对了。编译器不断给我的错误是:

error: expected primary-expression before '.' token

这是代码:

#include <iostream>
using namespace std;
class Exam{
private:
    string module,venue,date;
    int numberStudent;
public:
    //constructors:
    Exam(){
        numberStudent = 0;
         module,venue,date = "";
    }
//accessors:
        int getnumberStudent(){ return numberStudent; }
        string getmodule(){ return module; }
        string getvenue(){ return venue; }
        string getdate(){ return date; }
};
int main()
    {
    cout << "Module in which examination is written"<< Exam.module;
    cout << "Venue of examination : " << Exam.venue;
    cout << "Number of Students : " << Exam.numberStudent;
    cout << "Date of examination : " << Exam.date
    << endl;
    return 0;
}

问题要求使用访问器和突变器,但我不知道为什么我应该使用突变器。

无论如何,不是 100% 确定它们是如何工作的。

在你的class Exam中:modulevenuedate是私有成员,只能在此类的范围内访问。即使您将访问修饰符更改为 public

class Exam {
public:
    string module,venue,date;
}

这些仍然是与具体对象(此类的实例)相关联的成员,而不是与类定义本身(如static成员一样)。若要使用此类成员,需要一个对象:

Exam e;
e.date = "09/22/2013";

等。另请注意,module,venue,date = "";不会以任何方式修改modulevenue,您的实际意思是:

module = venue = date = "";

尽管std::string对象会自动初始化为空字符串,但无论如何,此行都是无用的。

您需要突变器函数来接受用户的输入以存储在变量模块、地点和日期中

例:

void setdetails()
{
    cin.ignore();
    cout<<"Please Enter venue"<<endl;
    getline(cin,venue);
    cout<<"Please Enter module"<<endl;
    getline(cin,module);
}//end of mutator function