C++ 我们应该如何在结构中添加函数? #包括 使用名称空间std; 结构教师 { int-id; 字符名[50]; 国际工资; 无效输入(教师a) { cout>a.name; cout>a.id; 工资; } 无效输出(教师b) { 这看起来像是一个奇怪的设计,为什么你的类方法不直接对这个进行操作呢 #include <iostream> using namespace std; struct teacher { int id; char name[50]; int salary; void input(teacher a) { cout << "Enter Name : "; cin >> a.name; cout << "Enter ID : "; cin >> a.id; cout << "Enter Salary : "; cin >> a.salary; } void output(teacher b) { cout << "Your Name Is : " << b.name << endl; cout << "Your ID Is : " << b.id << endl; cout << "Your Salary Is : " << b.salary; } }; int main() { teacher t; t.input(t); t.output(t); return 0; }

C++ 我们应该如何在结构中添加函数? #包括 使用名称空间std; 结构教师 { int-id; 字符名[50]; 国际工资; 无效输入(教师a) { cout>a.name; cout>a.id; 工资; } 无效输出(教师b) { 这看起来像是一个奇怪的设计,为什么你的类方法不直接对这个进行操作呢 #include <iostream> using namespace std; struct teacher { int id; char name[50]; int salary; void input(teacher a) { cout << "Enter Name : "; cin >> a.name; cout << "Enter ID : "; cin >> a.id; cout << "Enter Salary : "; cin >> a.salary; } void output(teacher b) { cout << "Your Name Is : " << b.name << endl; cout << "Your ID Is : " << b.id << endl; cout << "Your Salary Is : " << b.salary; } }; int main() { teacher t; t.input(t); t.output(t); return 0; },c++,C++,如果可能的话,我更喜欢使用std::string而不是char[]。在input()中修改参数a,该参数在到达函数末尾时超出范围 相反,您应该修改类成员变量本身 int main() { teacher t; t.input(); t.output(); return 0; } void输入() { 姓名; cout>id; 工资; } Unrelated:drop使用命名空间std;,改用std::cout。用std::string替换char数组。不要使用

如果可能的话,我更喜欢使用
std::string
而不是
char[]

input()
中修改参数
a
,该参数在到达函数末尾时超出范围

相反,您应该修改类成员变量本身

int main()
{
    teacher t;
    t.input();
    t.output();

    return 0;
}
void输入()
{
姓名;
cout>id;
工资;
}

Unrelated:drop
使用命名空间std;
,改用
std::cout
。用
std::string
替换
char
数组。不要使用
std::endl
改用
“\n”<代码> >不要通过<代码>老师>代码>输入/输出<代码>,使用<代码>类<代码>代替“代码>结构>代码>。这是一个旁注:我目前正在学习OOP,所以在使用类之前,我尝试用结构来做。<代码>类< /COD>和<代码>结构> <代码>在C++、ONL中是功能上等价的。不同之处是它们的默认可见性(private用于
,public用于
结构
)。您可以使用/or。是的,使用char总是给我错误,我将尝试使用std::stringnow@QasimAhmed对SO表示感谢的方法是投票支持答案。
int main()
{
    teacher t;
    t.input();
    t.output();

    return 0;
}
void input()
{
    cout << "Enter Name : ";
    cin >> name;
    cout << "Enter ID : ";
    cin >> id;
    cout << "Enter Salary : ";
    cin >> salary;
}