与私人成员一起上课.这个代码出了什么问题
Classes with private member .. What is wrong with this code?
我是类的新手,我一直试图创建这个简单的类代码,但每次都会出错。当我不使用访问说明符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;
}
在主函数中,您正试图访问类的name
和ID
成员。哪些是私人的。。。由于您不在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
};
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 0-1背包代码中的错误.我的代码中有什么错误
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 这行代码在C++类中意味着什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 以下 C++ 代码用于 -> "#define idiv(a, b) (((a) + (b) / 2) / (b))" 是什么?
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 此代码中的操作流程是什么?C/C++.
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 此代码验证公式是什么意思?
- 需要以下代码的帮助,下面的代码有什么问题
- C++标准提案代码:什么是 N 和 P?
- C - 哈希算法代码什么都没有返回
- 将"12345678"转换为"1-234-5678",我的代码什么也没产生
- 在编译过程中,琐碎的(没有效果的)代码什么时候会被删除
- 有人能告诉我为什么这个代码什么都不打印吗