1. 面向对象小例子
#includeusing namespace std;class bad_hmean {private: double v1; double v2;public: bad_hmean (int a=0, int b=0): v1(a), v2(b){}; // 上下这么写是一样的意思 , 有时候看见上面的都不知道什么意思, 所以这里也就记录一下 // bad_hmean (int a=0, int b=0){v1=a, v2=b}; // virtual ~bad_hmean (); void mesg();};inline void bad_hmean::mesg(){ std::cout << "hmean(" << v1 << ", " << v2 << "): " << "invalid arguments: a = -b\n" << '\n';}int main(int argc, char const *argv[]) { bad_hmean(1, 2).mesg(); // bg.mesg(); return 0;}
下面是经常写的, 高级封装, 把类进行拆分, 类和方法分开的形式
// 目录和文件都小写, 重要的事情才大写// 类的名字首字母大写#include#include #include "Per.h"Person::Person(){ std::cout << "构造函数: " << this->testAbc << '\n';}Person::~Person(){ std::cout << "析构函数: " << this->testAbd << '\n';}void Person::setpid(int pid){ this->_pid = pid; // this 表示当前对象下的_pid}int Person::getpid(){ return this->_pid;}void Person::setname(string name){ this->_name = name;}string Person::getname(){ return _name;}void Person::setage(int age){ this->_age = age;}int Person::getage(){ return _age;}int main(){ // 锦绣城, 双滦区 2区观鱼园 // -----普通方式----- // /* Person per; per.setpid(1); per.setname("tom"); per.setage(20); int pid = per.getpid(); string name = per.getname(); int age = per.getage(); std::cout << "pid: " << pid << " "; std::cout << "name: " << name<< " "; std::cout << "age: " << age << '\n'; */ // -----指针方式-----// Person *per = new Person(); per->setpid(1); per->setname("Baker"); per->setage(20); int pid = per->getpid(); string name = per->getname(); int age = per->getage(); // delete前打印的 // std::cout << "pid: " << pid << " "; std::cout << "name: " << name<< " "; std::cout << "age: " << age << '\n'; delete per; // delete 后打印的 // std::cout << "pid: " << pid << " "; std::cout << "name: " << name<< " "; std::cout << "age: " << age << '\n'; return 0;}
#include#include using namespace std;class Person{ private: int _pid; string _name; int _age; public: int testAbc = 123; int testAbd = 124; Person(); ~Person(); void setpid(int pid); int getpid(); void setname(string name); string getname(); void setage(int age); int getage();};