C++编程填空:构造与析构
其他问答
1
描述
请完善程序,使得所有类型能够正确初始和消亡
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
// 在此处补充你的代码
int main(){
int n;
cin >> n;
for (int i = 1; i<=n; i++) {
int x;
cin >> x;
if (x == 0) {
A *a = new A();
delete a;
}else {
A *a = new B();
delete a;
}
}
return 0;
}
样例输入
3
1 0 1
样例输出
New A
New B
Delete B
Delete A
New A
Delete A
New A
New B
Delete B
Delete A
-
class Clock { public: Clock(int NewH, int NewM, int NewS); //构造函数 void SetTime(int NewH, int NewM, int NewS); void ShowTime(); private: int Hour, Minute, Second; };
构造函数的实现:
Clock::Clock(int NewH, int NewM, int NewS) { Hour=NewH; Minute=NewM; Second=NewS; } 建立对象时构造函数的作用: int main() { Clock c(0,0,0); //隐含调用构造函数,将初始值作为实参。 c.ShowTime(); return 0; }
-
class A { public: A(){cout<<"New A"<<endl;} virtual ~A(){cout<<"Delete A"<<endl;} }; class B:public A { public: B(){cout<<"New B"<<endl;} virtual ~B(){cout<<"Delete B"<<endl;} };
发表回复