1. 静态对象
#include<iostream>
#include<string>
using namespace std;
#if 0
class student {
private:
int id;
string name;
int age;
string sex;
public:
void set(int id,string name,int age,string sex) {
this->id = id;
this->name = name;
this->age = age;
this->sex = sex;
}
void get() {
cout << id <<" "<< name<<" " << age <<" "<< sex << endl;
}
};
int main() {
student st;
st.set(1, "李三", 23, "f");
st.get();
}
#endif
2. 动态对象数组
#include<iostream>
#include<string>
using namespace std;
#if 0
class animal {
private:
int id;
string name;
int age;
public:
void eat() {
cout <<name<< "吃草"<<endl;
}
void drink() {
cout <<name<< "喝水"<<endl;
}
animal() {
cin >> id;
cin >> name;
cin >> age;
}
animal(int id,string name,int age) {
this->id = id;
this->name = name;
this->age = age;
}
void show() {
cout << id << name << age<<endl;
}
};
int main() {
animal a;
animal a1[3]{ {1,"cat",5},{2,"dog",7}, {3,"tiger",10} };
animal a2(4, "pandas", 6);
a1[0].eat();
a1[1].eat();
a1[2].eat();
a2.eat();
a.drink();
cout << "-------------------" << endl;
animal *p = new animal(4, "pandas", 6);
animal *p1 = new animal[3] {{1,"cat",5},{2,"dog",7}, {3,"tiger",10}};
p->show();
p1[0].show();
p1[1].show();
p1[2].show();
p1->show();
(p1 + 1)->show();
(p1 + 2)->show();
delete p;
delete[]p1;
}
#endif
3. 友元函数
#include<iostream>
#include<string>
using namespace std;
#if 0
class student {
private:
int id;
string name;
int age;
public:
student(int id, string name, int age) {
this->id = id;
this->name = name;
this->age = age;
}
friend void show(student &s);
};
void show(student &s) {
cout << s.id << s.name << s.age<<endl;
}
int main() {
student s(1,"张三",18);
show(s);
student s1[2]{{2,"李四",24},{3,"王五",22}};
show(s1[0]);
show(s1[1]);
}
#endif
|