Object-Oriented Programming
struct Person{
int id;
string name;
int height, weight;
};
struct Person{
int id;
string name;
int height, weight;
};
Person teacher, students[30];
struct Person{
int id;
string name;
int height, weight;
};
Person teacher, students[30];
這時候它們的 id 和各個數值會是多少?
本來的預設值
struct Person{
int id;
string name;
int height, weight;
};
Person teacher, students[30];
teacher.id = 1;
teacher.name = "yungyao";
teacher.height = 180;
teacher.weight = 60;
for (int i=0;i<30;++i){
students[i] = ...
...
}
是不是要寫的東西有點多?
struct Person{
int id;
string name;
int height, weight;
Person(int _id, string _name, int _height, int _weight){
id = _id;
name = _name;
height = _height;
weight = _weight;
}
};
Person teacher, students[30];
teacher = Person(1, "yungyao", 180, 60);
for (int i=0;i<30;++i){
students[i] = Person(...);
}
struct Person{
static int personCount = 0;
int id;
string name;
int height, weight;
Person(string _name, int _height, int _weight){
id = personCount;
personCount++;
name = _name;
height = _height;
weight = _weight;
}
};
Person teacher, students[30];
teacher = Person("yungyao", 180, 60);
for (int i=0;i<30;++i){
students[i] = Person(...);
}
struct Person{
static int personCount = 0;
int id;
string name;
int height, weight;
Person(string _name, int _height, int _weight){
...
}
void speakName(){
cout << "I am " << name << ".\n";
}
};
...
teacher.speakName(); // I am yungyao.
struct Person{
static int personCount = 0;
int id;
string name;
int height, weight;
Person(string _name, int _height, int _weight){
...
}
double BMI(){
return weight / height / height;
}
};
...
return teacher.BMI();
struct Person{
static int personCount = 0;
int id;
string name;
int height, weight;
Person(string _name, int _height, int _weight){
...
}
void gainHeight(int gainedHeight){
height += gainedHeight;
}
};
...
cout << teacher.height << '\n'; // 180
teacher.gainedHeight(-20);
cout << teacher.height << '\n'; // 160
struct Classroom{
Person teacher;
Person student[40];
int studentCount;
Classroom(int _studentCount, Person _teacher){
teacher = _teacher;
studentCount = _studentCount;
for (int i=0;i<studentCount;++i){
student = Student("unknown", 140, 40);
}
}
};
(for C++)
struct Person{
static int personCount = 0;
int id;
string name;
private:
int height, weight;
Person(string _name, int _height, int _weight){
...
}
double BMI(){
return weight / height / height;
}
};
...
cout << teacher.height; // Compile Error: Can not access private
class Person{
string name;
public:
void printName(){
cout << name << endl;
}
};
class Student: public Person{
int number;
public:
void printNumber(){
cout << number << endl;
}
};
class Person{
string name;
public:
void printName(){
cout << name << endl;
}
};
class Student: public Person{
int number;
public:
void printName(){
cout << name << ' ' << number << endl;
}
};