C++ 将字符串存储到类中

标签 c++ visual-studio

我之前做了一个关于结构的话题。而且我知道类与结构具有相同的概念。我将如何将字符串存储到类中?

这是类

class studentType
{
public:
    void setData(string, int);
    string getName() const;
    int getId() const;
private:
    string name;
    int sid;
};

void studentType::setData(string, int) {
    name = ??;
    sid = ??;
}

string studentType::getName() const {
    return name;
}

int studentType::getId() const {
    return sid;
}

主要包括:

int main() {

    studentType object, number;

    cout << "enter name and code of item1: ";
    cin >> object.setData() >> object.setData();
    cout << "enter name and code for item2: ";
    cin >> number.setData() >> number.setData();

    system("pause");
    return 0;
}

我该如何解决 cin 问题?我已经在 header 中定义了字符串。是的,我知道使用命名空间标准;不是首选,但为了简单起见

最佳答案

int id;
string name;
cout << "enter name and code of item1: ";
cin >> name >> id;
object.setData(name, id);
cout << "enter name and code for item2: ";
cin >> name >> id;
object.setData(name, id);

不过,您应该为您的类使用构造函数:

class studentType {
public:
    studentType(string name, int sid)
        : name(name)
        , sid(sid)
    { }
// ...

然后您可以使用正确的名称和 ID 初始化您的对象:

cin >> name >> id;
studentType object(name, id);

但我想构造函数很快就会出现在您当前正在学习的教程或类(class)中。

关于C++ 将字符串存储到类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707634/

相关文章:

c# - 为什么 add-migration 命令没有创建迁移?不识别包裹

c++ - 将函数声明为 pure 或 const 对 GCC 的影响(如果不是)

c++ - 是否有任何 STL 实现支持 C++ 概念?

c++ - std::map 可以包含对构造函数的引用吗?

C++ MFC 消息处理

c# - 无法开始调试。无法启动启动项目。 VS2015

visual-studio - mspdbsrv.exe 永生?

c++ - MFC 数据交换验证

目标框架列表中缺少 .NET Framework 4.5

c# - 删除 Visual Studio 中未使用的代码