从java视角看待c++代码的一些写法,挺有意思
1. 一个文件未必只定义一个类。实际上,
有的函数和变量可以不属于任何类
//playcpp.cpp文件
int main(){
cout << "hello world! ";
return 0;
}
2.
函数一般先声明,再定义
int doSum(int a, int b); //声明
int main(){
cout << "hello world! " << doSum(3, 5);
return 0;
}
int doSum(int a, int b){ //定义
return a + b;
}
3.
类与对象的写法
//声明类,当前文件是Person.h
class Person{
private: //注意冒号
int age;
public:
int get_age(); //只是声明,不是定义
}; //注意分号
//这是另一个文件
#include <iostream>
#include "Person.h" //包含类的声明文件
using namespace std;
//成员函数的定义可以写在类声明的外面
int Person::get_age(){ //要使用Person::这个类名前缀
return 99;
}
int main(){
//创建对象
Person p; //不需要new
cout << p.get_age() << "\n";
//指针式写法
Person *p2 = new Person; //通过指针动态分配内存
cout << p2 -> get_age() << endl;
delete p2;
}
4.
继承的写法
//子类的声明,当前文件是GoodPerson.h
class GoodPerson:public Person{
public:
void do_good_stuff();
};
#include <iostream>
#include "Person.h"
#include "GoodPerson.h" //包含子类的头文件
int main(){
//子类
GoodPerson *gp = new GoodPerson;
gp -> do_good_stuff();
delete gp;
}
void GoodPerson::do_good_stuff(){
cout << "I am a good man. I do godd stuff" << endl;
}