在c++中是否可以在代码体中声明一个属性?

Is it possible in C++ to declare an attibute in the body?

本文关键字:一个 属性 是否 c++ 代码 声明      更新时间:2023-10-16

在c++中是否可以在主体(即.cpp文件)中声明属性?

如果您所说的attribute是指类的member variable,那么答案是:"成员变量必须在类定义中定义。"它们不能在其他任何地方定义,既不能在构造函数中定义,也不能在任何成员函数中定义。

类定义是在头文件中还是在源文件(.cpp)中都不重要。

你不能在类的原始定义之外添加属性(通常在头文件中),例如在.cpp文件中

是:

test.cpp:
class Test
{
   int x; //declare attribute in class body and in cpp file
};