※ 本文轉寄自 ptt.cc, 文章原始頁面
[問題] 類別、建構子問題
程式新手
前幾天寫了一個練習題拿去問chatgpt
#include <iostream>
using namespace std;
class Animal {
public:
string name;
Animal(string, string, int);
void print1();
protected:
string type;
int weight;
};
Animal::Animal(string n, string t, int w) {
name = n;
type = t;
weight = w;
}
void Animal::print1() {
cout << "name:" << name << " type:" << type << " weight:" << weight;
}
class Cat : public Animal {
public:
Cat(string, string, int, int, int);
void print2();
private:
int body_length;
int tail_length;
};
Cat::Cat(string n, string t, int w, int b, int a)
: Animal(n, t, w), body_length(b), tail_length(a) {}
void Cat::print2() {
print1();
cout << " body length:" << body_length << " tail length:" << tail_length;
}
class Human : public Animal {
public:
Human(string, string, int, int, string);
void print3();
Cat pet;
protected:
int height;
};
Human::Human(string n, string t, int w, int h, string p)
: Animal(n, t, w), height(h) {
pet = Cat(p, "black", 7, 30, 20);
}
void Human::print3() {
print1();
cout << " height:" << height << " pet:" << pet.name << endl;
}
int main() {
Human Betty("Betty", "Asian", 46, 160, "Kitty");
Betty.print3();
Betty.pet.print2();
return 0;
}
結果竟然沒辦法執行xdd
後來回覆他後他又生了一個程式給我,基本上就是把黃字的部分改成
Human::Human(string n, string t, int w, int h, string p)
: Animal(n, t, w), height(h), pet(p, "black", 7, 30, 20) {}
這樣
但是這兩個有什麼不同啊@@他解釋給我聽但是我聽不懂....
但是這兩個有什麼不同啊@@他解釋給我聽但是我聽不懂....
請教板上高手!
----
Sent from BePTT on my OPPO CPH1943
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.217.31.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1695028575.A.715.html
50 則留言
amamoimi 作者的近期文章
[問題] temporary 可以take reference 嗎?
c++新手最看了一些文章,發現一個問題,舉個例子: #include <iostream> class A{ public: int a=5; int& g(){ return a; } A f(){ return *t
[問題] 用函數設定參照的問題
各位晚安打擾了 https://onlinegdb.com/_DyNuxd2H 我一直不太明白為什麼為什麼這樣寫是合法的 f(a)=5這行不是在把function call設值嗎 但是照理來說只能assign value給變數吧?(gpt這
[問題]char 指標問題
不好意思我程式新手又來擾民了@@ https://onlinegdb.com/Vm941gQ0_ 這是我在書上看到的程式碼 功能是把變數byte by byte的交換 但是我看不太懂那個swap函數... 為什麼可以隨便把參數冠上一個(ch
[問題] 遞迴函數的變數儲存
不好意思又是我c++新手 想問一個問題 舉個例子 #include<iostream> using namespace std; void f(int); int main(){ f(2); return 0;} void f(
→
→
→
→
→
→
推
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→
推
→
→
→
→
→
→
→
→
→
→
→
→
→
→
→