晕了,因为面向对象编程是以后的必修课,现在想先学一下c++函数式编程,结果还是逃不了。幸好之前学过python面向对象,重温一下吧
//调用操作符重载
//之前虽然学过python面向对象,但是还是有必要学习c++的——为FP准备
#include <iostream>
#include <string>
using namespace std;
typedef void return_type ;
typedef void arguments;
//对之前代码的理解
int ask() { return 42; }//ask函数名,返回int类型变量42
typedef decltype (ask)* function_ptr;// function_ptr是指向ask返回数据类型的指针
class convertible_to_function_ptr {
public:
operator function_ptr() const//我们将convertivle_to_function_ptr定义为了指向ask函数的int*类型
{
return ask;
}
};//operator作类的转换函数
/*int main(int argc, char* argv[])
{
auto ask_ptr = &ask;
cout << ask_ptr() << endl;
auto* ask_ref1 = ask;
auto& ask_ref2 = ask;
cout << ask_ref1() << ' ' << ask_ref2 << endl;//加括号直接调用子程序,不加括号可以显示子程序储存的地址
convertible_to_function_ptr ask_wrapper;//指向ask函数的int*类型,这种数据类型有个新变量叫做ask_wrapper
std::cout << ask_wrapper() << endl;
}*/
//重载调用操作符的语法和定义成员函数一样简单——operator()需要指明返回值类型和函数所需要的参数
//e.g.
class funciont_object
{
public:
return_type operator()(arguments) const {
}
};
//C++面向对象,注意和python的区别,不需要self
//为类定义,其实没有定义任何数据,只定义了类的名称意味着什么
//也就是定义了类的对象包括了什么,以及可以执行哪些操作
//命名规范:每个单词都以大写字母开头,不包含下划线。
class Person {
public:
int gender;//1为男,0为女
int age;
//类的成员函数:那些把定义和原型写在类定义内部的函数
//它可以操作类的任意对象,可以访问对象中的所有成员
bool olderThan42(void) {
return age > 42 ? true : false;
}
bool isMale(void);
//类的访问修饰符,一个类可以有多个 public、protected 或 private 标记区域,默认访问修饰符是 private
private://私有成员变量或函数在类的外部是不可访问的,和封装特性有关
string personality;
public://一般在public定义访问的函数
void enterPersonality()
{
cout << "Enter personality: ";
cin >> personality;
};
void seePersonality()
{
cout << personality << endl;
}
};//protected可以在子类中访问,今晚继续。
//也可以在外部使用范围解析运算符::定义该函数,但是要在类中先声明
bool Person::isMale(void)
{
return gender == 1 ? true : false;
}
//person1,person2就是Person类的对象,下面做的是声明对象
Person person1;
Person person2;
//二者都有数据成员——也就是person.age这些
int main()
{
person1.gender = 1;
person1.age = 43;
person2.gender = 0;
person2.age = 17;
cout << person1.olderThan42()<<' '<< person2.isMale() << endl;
}