有没有办法创建驻留在另一个类中的类的实例
Is there a way you can create an instance of a class that resides within another class?
有没有办法创建一个驻留在另一个类中的类的实例?例如:
class foo
{
public:
foo()
{
//Constructor stuff here.
}
class bar
{
bar()
{
//Constructor stuff here.
}
void action(foo* a)
{
//Code that does stuff with a.
}
}
void action(bar* b)
{
//Code that does stuff with b.
}
}
现在我只想在我的 main() 中创建一个 bar 实例,如下所示:
foo* fire;
bar* tinder;
但 bar 未在此范围内声明。我在类中使用类的原因是因为它们都使用将另一个类作为参数的方法,但我需要在 main() 中为每个类创建一个实例。我能做什么?
您可以使用范围解析运算符:foo::bar* tinder;
。这将给你一个指向bar
的指针,而不是一个bar
对象。如果你想要那个,你应该做foo::bar tinder
.
但是,您没有充分的理由使用嵌套类。您应该将一个放在另一个之前,然后使用前向声明。像这样:
class foo; // Forward declares the class foo
class bar
{
bar()
{
//Constructor stuff here.
}
void action(foo* a)
{
//Code that does stuff with a.
}
};
class foo
{
public:
foo()
{
//Constructor stuff here.
}
void action(bar* b)
{
//Code that does stuff with b.
}
};
现在我只想在我的 main() 中创建一个柱线实例......
这是您将如何做到这一点:
int main()
{
foo::bar tinder;
}
bar
在foo
范围内声明。目前尚不清楚为什么会这样,因此除非您有充分的理由,否则不要使用嵌套类。另请注意,您尝试声明指向foo
和foo::bar
的指针,而不是实例。
类栏在类 foo 的范围内声明。所以你必须写
foo::bar* tinder;
此外,您忘记在类栏和foo的定义之后放置分号:)
嵌套类在另一个类的作用域内声明。因此,要从 main 使用它们,您需要告诉编译器在哪里可以找到该类。
这是语法:
foo::bar *tinder;
foo
是父作用域,bar
嵌套类。
希望它有帮助
你想要的是一个所谓的"嵌套类"。
你可以在这里找到你想知道的一切:为什么在C++中使用嵌套类?
例如:
class List
{
public:
List(): head(NULL), tail(NULL) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
相关文章:
- 如何将模板的实例传递给另一个模板的另一个实例?
- 如何在另一个类中创建类的实例?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 如何在C++中将类的实例完全重新分配给同一类的另一个实例(然后删除原始对象)?
- 无法从派生类型的作用域访问另一个实例的受保护成员
- 包含另一个实例的特征实例,该实例持有固定大小的特征对象
- 从模板类的另一个实例创建模板类的实例时省略模板参数
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 对成员变量的引用在向同一向量中添加另一个实例后断开
- Object 创建另一个实例,而不是修改指向的实例
- 模板类实例接收不同类型的相同模板类的另一个实例
- Qt5:阻止应用程序的另一个实例不再有效...!
- 如何使模板类的一个实例与同一模板的另一个实例成为朋友
- 一个实例影响另一个实例,尽管它不应该't
- 从Python中的另一个实例获取实例
- 如何在c++中从一个实例访问另一个实例的信息
- 检查程序的另一个实例是否已经运行
- emacs:在另一个实例中自动打开相应的文件
- 在 c++ 中将一个 ascii 字符的所有实例替换为另一个实例
- 如何从另一个实例的类型动态实例化新实例?C++