C++中 :: 的用途

Uses of :: in C++

本文关键字:C++      更新时间:2023-10-16

所以在人们告诉我谷歌之前,我有,这就是我在这里的原因。

我的问题是——

如何 :: 能够用于构造函数以外的事物?

我知道构造函数的正确规则是它们必须与它们所属的类具有相同的名称。但是在此代码中,无论如何都会使用它。有人可以告诉我为什么以及如何?

编辑:我忘了提,第一个块是头文件,第二个是所述头的 cpp 源。


class Rainbow{
public:
static void registerItems();//Does exactly what it says
static void initClientData();//Initializes stuff like icon and texture
static void initCreativeItems();//Adds them to the creative inventory

static Item* mSword;//This is our item. 
};

void Rainbow::registerItems(){
mSword = new SwordItem(3000);//Add our sword object to our SwordItem class
}
void Rainbow::initClientData(){
mSword->setIcon("rainbow_sword",0);//Sets its icon image
}
void Rainbow::initCreativeItems(){
Item::addCreativeItem(3000,0);//Uses the ID to add it to the creative inventory
}

每当在另一个命名事物中找到给定名称时,就会使用::符号,但包含的事物不是对象(而是类、命名空间或枚举(。

namespace n {
struct s {
enum e {
q
};
};
}
n::s::e my_value = n::s::e::q;

它是左关联的,所以在这种情况下,en::s内部找到,qn::s::e内部。

您谈论的是范围解析运算符 (::)。它用于描述范围。

int a=5;   //Global Variable
int main() {
int a=1;  //local variable
cout<<a;
cout<<::a;  //We are explicitly mentioning that we need the global scope 'a' variable
return 0;
}

输出:

1 5

构造函数只是一个方法,您可以创建自己的方法来初始化日期成员。创建对象时会自动调用构造函数(与类同名(。

通常,将在创建时调用默认构造函数来初始化对象,这是自动的。 然后,可以显式调用方法来为所需的数据成员设置值。

有关您的情况的正确解释,请查看此答案的顶部评论

相关文章:
  • 没有找到相关文章