簡體   English   中英

C++ Class 獲得輸入

[英]C++ Class getting input

我想問你一個快速的問題。 如何獲取姓名、姓氏、身份證和年齡作為輸入? 這些必須作為輸入,並且變量必須是私有的。 我應該如何編碼?

#include <iostream>
using namespace  std;

class Employee{
private:
    string  Name;
    string Surname;
    int IdNumber;
    int age;
public:
    Employee(string isim,string soyisim,int idnumarasi,int yas){

        Name = isim;
        Surname = soyisim;
        IdNumber = idnumarasi;
        age = yas;
    }
      void printEmployee(){

          cout << Name << endl;
          cout << Surname << endl;
          cout << IdNumber <<endl;
          cout << age << endl;
    }


};


int main() {



    Employee employee("John","Lares",12,25);

    employee.printEmployee();


    return 0;
}

編輯版。 我使用了 getline 但仍然無法訪問私有變量。 怎樣才能達到私有變量。 getter setter 函數的唯一方法是什么?

#include <iostream>
using namespace  std;

class Employee{
private:
    string  Name;
    string Surname;
    int IdNumber;
    int age;
public:
    Employee(){

        Name = isim;
        Surname = soyisim;
        IdNumber = idnumarasi;
        age = yas;
    }
      void printEmployee(){

          cout << Name << endl;
          cout << Surname << endl;
          cout << IdNumber <<endl;
          cout << age << endl;
    }


};


int main() {



    Employee employee();

    getline(cin,employee.Name);
    getline(cin,employee.Surname);
    getline(cin,employee.IdNumber);
    getline(cin,employee.age);

    employee.printEmployee();


    return 0;
}


一種簡單的方法是使用您定義的構造函數

int main()
{
    string name, surname;
    int id, age;
    cin >> name >> surname >> id >> age;       // read user input
    Employee someone(name, surname, id, age);  // create employee from user input
    ...
}

使用構造函數是為 class 成員變量賦予初始值的常規方法。

另一種更復雜的方法是重載operator>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM