示例
#include <iostream>
using namespace std;
class Person {
private:
string name;
int age;
public:
//构造函数
Person() {
}
Person(string s, int num):name(s), age(num) {//使用初始化列表对对象进行初始化
}
//析构函数
~Person() {
cout<<"\nThis object of "<<getName()<<" has been deleted.";
}
string getName(); //类函数(成员函数)声明
//类函数类内定义
int getAge() {
return age;
}
//运算符重载
int operator+(const Person& p) {
return this->age + p.age;
}
};
//类函数类外定义
string Person::getName() {
return name;
}
int main() {
Person p1("小明", 10);
//Person* p1 = new Person("小明", 10);
//cout<<p1->getName()<<p1->getAge()<<"岁。"
Person p2("小桃", 12);
cout<<p1.getName()<<"与"<<p2.getName()<<"年龄合计(岁):"<<p1 + p2;
return 0;
}