我是类(class)的新手,我一直在尝试创建这个简单的类(class)代码,但每次我都会遇到错误。当我不使用访问说明符 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;
}
最佳答案
在您的 main 函数中,您试图访问您的类的 name
和 ID
成员。哪些是私有(private)的...因为您不在 class Student
的范围内,编译器会对您大喊大叫。
你应该这样做(因为你已经实现了 setter 和 getter):
int ID(0);
std::string name;
std::cin >> name;
S.setName(name);
std::cin >> ID;
S.setID(ID);
关于c++ - 有私有(private)成员的类..这段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28501009/