c++ - 有私有(private)成员的类..这段代码有什么问题?

标签 c++ class object

我是类(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 函数中,您试图访问您的类的 nameID 成员。哪些是私有(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/

相关文章:

c++ - 在 C++11 中,我可以为非聚合类型实现类似构造函数的聚合类型初始化吗?如何实现?

javascript - 通过字符串名称引用对象成员?

php - 对象集合类与否

C++ 要求所有声明都有类型说明符

Java 目标/选择类/对象 - 困惑(抱歉标题不好)

c# - 我不明白为什么会出现此 "An Object Reference is Required"错误

c++ - send() 没有传送所有字节?

c++ - 使用默认构造函数指向对象的指针数组

c++ - 多重继承指定所需的虚函数而不重新定义它

c++ - 将实现注入(inject)到 C++ 中的类中