与私人成员一起上课.这个代码出了什么问题

Classes with private member .. What is wrong with this code?

本文关键字:代码 什么 问题 成员 一起上      更新时间:2023-10-16

我是类的新手,我一直试图创建这个简单的类代码,但每次都会出错。当我不使用访问说明符private时,它工作得很好,但我想练习如何使用private。你能告诉我怎么了吗?

#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
    string name;
    int ID;
public:
    void setName(string);
    string getName();
    void setID(int);
    int getID();
};
void Student::setName(string n)
{
    name=n;
}
string Student::getName()
{
    cout<<name;
    return name;
}
void Student::setID(int i)
{
    ID=i;
}
int Student::getID()
{
    cout<<ID;
    return ID;
}
int main ()
{
    Student S;
    cout<<"Enter Student name: ";
    cin>>S.name;
    cout<<"Enter students ID: ";
    cin>>S.ID;
    cout<<"The student's name is "<< S.name<<endl;
    cout<<"The student's ID is "<< S.ID<<endl;
    return 0;
}

在主函数中,您正试图访问类的nameID成员。哪些是私人的。。。由于您不在class Student的范围内,编译器会对您大喊大叫。

您应该这样做(因为您已经实现了setter和getter):

int ID(0);
std::string name;
std::cin >> name;
S.setName(name);
std::cin >> ID;
S.setID(ID);

您必须使用setter/getter来访问您的私有字段以设置或检索它们的值,您不能将它们与class dot notation一起使用,因为它们是私有的,并且您只能使用公共方法

来访问它们

问题是:您在访问私有成员时没有使用类成员函数(在类范围之外)。

当您希望保护某个值免受不受控制的访问时,私有成员非常有用。比如,值的修改必须经过一定的验证(这将在类函数中实现)。

在代码中,您确保name和ID是私有的,这意味着只能使用类函数(如构造函数或getter和setter)来访问它们。

如果需要,可以创建一个名为"教室"的类(其中包含许多学生,存储在向量中)。

在该类中,您可以确保在添加学生时,其ID是自动生成的,并且不等于任何其他ID。在这种情况下,将学生向量设置为私有向量非常重要,因为它需要某种验证。

    class Student
{
private: // anything that wants to access members below
        //  this must be defined as a class member, or the equivalent
    string name; 
    int ID;
public:
    void setName(string); // can access private members
    string getName(); // can access private members.... should be const
    void setID(int); // can access private members
    int getID(); // can access private members, should be const
};