2013-09-22 69 views
4

我只想说我仍然在学习C++,所以我开始使用有关类和结构的模块,虽然我不明白所有的东西,但我认为我有点正确。编译器一直给我的错误是:C++错误 - 预期'。'之前的主表达式令牌|

错误:期望在'。'之前的主表达式。令牌|

这里是代码:

#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%肯定它们是如何工作的。

请帮忙。

回答

10

在您的class Exammodule,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对象自动初始化为空字符串,因此该行无论如何都是无用的。

0

您需要的存取器功能,以接受来自用户的输入您的变量来存储模块,地点和日期

例:

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

请格式化,并提供完整的示例代码。 –

相关问题