**
程序改错
**
【问题描述】请修改下列程序,尽量减少增行或者减行,当输入2时,程序的运行结果如下:
The number of all students:0
The number of all students:1
The number of all students:0
The number of all students:2
The number of all students:2
要求:类中数据成员连同访问属性均不可以修改。
错误程序源码如下:
#include
using namespace std;
class Student{
public:
Student(){
total++;
}
~Student(){ }
Student(char *p="wang");
static int get_total();
private:
char name[20];
static int total;//用来统计学生总人数
};
static int Student::total=0;
Student::Student(char *p=“wang”){
strcpy(name,p);
total++;
}
static int Student::get_total(){
return total;
}
int main(){
cout<<"The number of all students:"<<Student::total<<endl;
Student *p=new Student("Li");
cout<<"The number of all students:"<<p->get_total()<<endl;
delete p;
cout<<"The number of all students:"<<Student::total<<endl;
int n;
cin>>n;
Student *s= new Student [2];
for(int i=0;i<n;i++)
cout<<"The number of all students:"<<s[i].total<<endl;
return 0;
}
#include<iostream>
#include<cstring>
using namespace std;
class Student
{
public:
Student(){total++;}
~Student(){total--;}
static int get_total();
private:
char name[20];
static int total;//用来统计学生总人数
};
int Student::total=0;
int Student::get_total()
{
return total;
}
int main()
{
cout<<"The number of all students:"<<Student::get_total()<<endl;
Student *p=new Student;
cout<<"The number of all students:"<<p->get_total()<<endl;
delete p;
cout<<"The number of all students:"<<Student::get_total()<<endl;
int n;
cin>>n;
Student *s=new Student [n];
for(int i=0;i<n;i++)
cout<<"The number of all students:"<<s[i].get_total()<<endl;
delete []s;
return 0;
}
博客围绕C++程序改错展开,要求修改给定程序,尽量少增行或减行,当输入2时达到特定运行结果,且类中数据成员及访问属性不可修改,给出了错误程序源码。

2825

被折叠的 条评论
为什么被折叠?



