#include<iostream> #include<string> using namespace std; class Cstudent{ private: int number; string name; static int total; static int actualtotal; public: Cstudent(string name); Cstudent(const Cstudent &p); ~Cstudent(); void showstudent(); int getnumber(){return number;} static int gettotal(){return total;} static int getactualtotal(){return actualtotal;} }; int Cstudent::total =0; int Cstudent::actualtotal=0; Cstudent::Cstudent(string name){ name = name; number = ++total; actualtotal++; } Cstudent::Cstudent(const Cstudent &p){ name = p.name; number = ++total; actualtotal++; } Cstudent::~Cstudent(){ actualtotal--; } void Cstudent::showstudent(){ cout << "student's name is " << name << "\tnumber is " <<number << endl; } int main(){ Cstudent stu[10]; for(int i=0;i<10;i++) stu[i].showstudent(); cout<<Cstudent::gettotal()<<stu[0].getactualtotal()<<endl;//两种访问静态方法 Cstudent *pa = new Cstudent("wang"); pa->showstudent(); delete pa; Cstudent *pb; pb = new Cstudent[10]; for(int i=0;i<10;i++) pb[i].showstudent(); delete[]pb; return 0; }哪里错了
时间: 2024-03-04 16:48:46 浏览: 55
在类的构造函数中,私有成员变量`name`应该使用`this->name`来表示当前对象的`name`成员变量,而不是将函数参数`name`赋值给自身`name`变量。因此,`Cstudent`类的构造函数应该改为:
```
Cstudent::Cstudent(string name){
this->name = name;
number = ++total;
actualtotal++;
}
```
此外,在输出`Cstudent`对象的实际数量时,应该在两个数之间添加空格或者其他分隔符,否则两个数会被拼接在一起,难以区分。因此,`main`函数中输出实际数量的代码应该改为:
```
cout << Cstudent::gettotal() << " " << stu[0].getactualtotal() << endl;
```
以上修改后的完整代码如下:
```
#include<iostream>
#include<string>
using namespace std;
class Cstudent{
private:
int number;
string name;
static int total;
static int actualtotal;
public:
Cstudent(string name);
Cstudent(const Cstudent &p);
~Cstudent();
void showstudent();
int getnumber(){return number;}
static int gettotal(){return total;}
static int getactualtotal(){return actualtotal;}
};
int Cstudent::total =0;
int Cstudent::actualtotal=0;
Cstudent::Cstudent(string name){
this->name = name;
number = ++total;
actualtotal++;
}
Cstudent::Cstudent(const Cstudent &p){
name = p.name;
number = ++total;
actualtotal++;
}
Cstudent::~Cstudent(){
actualtotal--;
}
void Cstudent::showstudent(){
cout << "student's name is " << name << "\tnumber is " <<number << endl;
}
int main(){
Cstudent stu[10];
for(int i=0;i<10;i++)
stu[i].showstudent();
cout << Cstudent::gettotal() << " " << stu[0].getactualtotal() << endl;//两种访问静态方法
Cstudent *pa = new Cstudent("wang");
pa->showstudent();
delete pa;
Cstudent *pb;
pb = new Cstudent[10];
for(int i=0;i<10;i++)
pb[i].showstudent();
delete[]pb;
return 0;
}
```
阅读全文