C++/Class/inline
Содержание
Automatic inline
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
// automatic inline
void init(int i, int j) {
a = i;
b = j;
}
void show() {
cout << a << " " << b << endl;
}
};
int main() {
myclass x;
x.init(10, 20);
x.show();
return 0;
}
Create an inline function.
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
void init(int i, int j);
void show();
};
// an inline function.
inline void myclass::init(int i, int j)
{
a = i;
b = j;
}
// another inline function.
inline void myclass::show()
{
cout << a << " " << b << endl;
}
int main()
{
myclass x;
x.init(10, 20);
x.show();
return 0;
}
Creating Inline Functions Inside a Class
#include <iostream>
using namespace std;
class MyClass {
int i;
public:
int get_i(void) { return i; }
void put_i(int j) { i = j; }
} ;
main(void)
{
MyClass s;
s.put_i(10);
cout << s.get_i();
return 0;
}
Inline functions may be class member functions
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
void init(int i, int j);
void show();
};
// Create an inline function.
inline void myclass::init(int i, int j)
{
a = i;
b = j;
}
// Create another inline function.
inline void myclass::show()
{
cout << a << " " << b << "\n";
}
int main()
{
myclass x;
x.init(10, 20);
x.show();
return 0;
}
Inline function that calculates the volume of a sphere
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <cmath>
const double PI = 3.14159;
inline double sphereVolume( const double r )
{ return 4.0 / 3.0 * PI * pow( r, 3 ); }
int main()
{
double radius;
cout << "Enter the length of the radius of your sphere: ";
cin >> radius;
cout << "Volume of sphere with radius " << radius <<
" is " << sphereVolume( radius ) << endl;
return 0;
}
Use inline to make this program more efficient
#include <iostream>
using namespace std;
class MyClass {
int i;
public:
int get_i(void);
void put_i(int j);
} ;
inline int MyClass::get_i(void){
return i;
}
inline void MyClass::put_i(int j){
i = j;
}
main(void){
MyClass s;
s.put_i(10);
cout << s.get_i();
return 0;
}