7

我只想说我还在学习 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% 确定它们是如何工作的。

4

2 回答 2

14

在你的class Exam:module和是私有成员venuedate只能在这个类的范围内访问。即使您将访问修饰符更改为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对象会自动初始化为空字符串,但无论如何这行都没用。

于 2013-09-22T09:32:58.357 回答
-1

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

例子:

void setdetails()
{
    cin.ignore();
    cout<<"Please Enter venue"<<endl;
    getline(cin,venue);
    cout<<"Please Enter module"<<endl;
    getline(cin,module);
}//end of mutator function
于 2015-11-20T15:04:28.123 回答