Description
Description
實現如下animal類的子類cat類,使得調用示例可得到對應輸出。 提交時只需要提交cat類實現,不要提交animal類和main函數。 class animal{ public: animal(int age) : age(age) {} int age; }; class cat : public animal { public: cat(int age=1); static int getCatNum(int age); //返回貓的數量 //add any function or property here }; 調用示例: int main() { cat cat1; cout << cat::getCatNum() << endl; { cat cat2(2); cout << cat::getCatNum() << endl; cat cat3(cat2); cout << cat::getCatNum() << endl; } cout << cat::getCatNum() << endl; return 0; } 對應輸出: 1 2 3 1 考察點: 類繼承;靜態變量;構造函數、拷貝構造函數、析構函數; Problem Source: 12級期末機考題 |
#include<iostream>
using namespace std;
class animal{
public:
animal(int age) : age(age) {
this->age = age;
}
animal(){
age = 1;
}
int age;
};
class cat : public animal {
public:
cat(int age = 1){
this->age = age;
num++;
}
cat(cat &other){
num++;
this->age = other.age;
}
~cat(){
num--;
}
static int getCatNum(){ //返回貓的數量
return num;
}
//add any function or property here
private:
static int num;
};
int cat:: num = 0;
最終AC: :public animal(age)拯救一切
class cat : public animal {
public:
/*cat():animal(age){
age = 1;
num++;
}*/
cat(int age = 1) :animal(age){
this->age = age;
num++;
}
cat(cat &other) :animal(age){
num++;
this->age = other.age;
}
~cat(){
num--;
}
static int getCatNum(){ //返回貓的數量
return num;
}
//add any function or property here
private:
static int num;
};
int cat:: num = 0;
conclusion:繼承還有很多不懂的,期末考試要加油了。
Description
Description
實現如下animal類的子類cat類,使得調用示例可得到對應輸出。 提交時只需要提交cat類實現,不要提交animal類和main函數。 class animal{ public: animal(int age) : age(age) {} int age; }; class cat : public animal { public: cat(int age=1); static int getCatNum(int age); //返回貓的數量 //add any function or property here }; 調用示例: int main() { cat cat1; cout << cat::getCatNum() << endl; { cat cat2(2); cout << cat::getCatNum() << endl; cat cat3(cat2); cout << cat::getCatNum() << endl; } cout << cat::getCatNum() << endl; return 0; } 對應輸出: 1 2 3 1 考察點: 類繼承;靜態變量;構造函數、拷貝構造函數、析構函數; Problem Source: 12級期末機考題 |