类里面可以 - 定义成员函数
类里面可以 - 使用别名简化
#include <iostream>
#include <string>
using namespace std;
/* 定义一个Screen类 */
class Screen{
public:
/* 类中可以使用别名 作用域是整个类 */
typedef std::string::size_type index;
Screen (index ht = 0, index wd = 0):contents(ht * wd, 'A'),cursor(0),height(ht),width(wd){} // 构造函数
/* 写在类内部的函数都是内联函数 */
/* 类中也是可以定义重载函数的 具体定义了什么函数不需要关心,只是个演示 */
char get() const { return contents[cursor];}
char get(index r, index c) const
{
index row = r * width;
return contents[row + c];
}
private:
/* 具体定义了什么私有成员不需要关心,只是个演示 */
std::string contents;
index cursor;
index height, width;
}; // ";" 很重要
int main()
{
Screan a(10, 100);
cout << "test" << endl;
return 0;
}
类中内联成员函数的3种定义方法
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(const int &ag, const std::string &nm, const std::string &add):age(ag),name(nm),address(add){};
/* 第一种类内联定义方法 在类内直接定义 */
int getAge() const { return age; };
/* 第二种类内联定义方法 在类内声明函数 在外边定义inline函数 */
std::string getName() const;
/* 第三种类内联定义方法 在类内声明inline函数 在外边定义函数 */
inline std::string getAddress() const;
private:
int age;
std::string name;
std::string address;
};
/* 第二种类内联定义方法 在类内声明函数 在外边定义inline函数 */
inline std::string Person::getName() const { return name; }
/* 第三种类内联定义方法 在类内声明inline函数 在外边定义函数 */
string Person::getAddress() const { return address; }
int main()
{
Person a(15, "John", "shanghai");
cout << a.getName() << " " << a.getAge() << " " << a.getAddress() << endl;
cout << "test" << endl;
return 0;
}