C++之类成员函数
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Bird {
public:
double l;
double b;
double w;
double h;
double get_volume();
void set_value(double len, double breadth, double width, double height);
};
inline double Bird::get_volume() {
return l * b * w * h;
}
inline void Bird::set_value(double len, double breadth, double width, double height) {
l = len;
b = breadth;
w = width;
h = height;
}
Bird bird;
int main() {
system("chcp 65001");
bird.set_value(10, 20, 30, 40);
double volume = bird.get_volume();
cout << "体积为:" << volume << endl;
return 0;
}
输出:
Active code page: 65001
体积为:240000
在类内定义的函数就是成员函数,使用inline关键字修饰的就是内联函数,内联函数只有定义的时候才有效,在类内声明函数原型,在类外定义时使用inline修饰,若在函数原型前修饰,而在类外没有用inline修饰,则不是内联函数。
:: 叫作用域区分符,指明一个函数属于哪个类或一个数据属于哪个类。
:: 可以不跟类名,表示全局数据或全局函数(即非成员函数)。
#include <iostream>
#include <cstring>
using namespace std;
int year;
int month;
int day;
void set(int x, int y, int z) {
::year = x;
::month = y;
::day = z;
}
class Tdate {
public:
//成员函数
void set(int x, int y, int z) {
//非成员函数(全局函数)
::set(x, y, z);
}
private:
int year;
int month;
int day;
};
Tdate t_date;
int main() {
int x = 2021;
int y = 7;
int z = 20;
t_date.set(x, y, z);
cout << "year-month-day:" << year << "/" << month << "/" << day << endl;
return 0;
}
输出:
year-month-day:2021/7/20