学习 C++ 并查看类布局如下:
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
我知道 Java 和 Java 中的方法(函数)是在类中编写的。该类看起来像一个 Java 接口(interface)。我知道我可以这样写类(class):
class CRectangle {
int x, y;
public:
void set_values (int a, int b) {
x = a;
y = b;
};
int area () {return (x*y);}
};
但是有区别或标准吗?
最佳答案
有区别。当您在类定义中编写函数的定义时(情况 2),则认为该函数已被声明为 inline
。这是标准的 C++。
用法,是在类定义内,在头文件(.h)中声明成员函数(Java方法),在C++文件(.cpp,.cc,或.C, …) 这减少了编译时间,当您更改函数体时,只需编译 C++ 文件,而如果您更改头文件中的某些内容,则将编译包含此头文件的所有 C++ 文件。
关于C++ 基本类布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2864004/