如何在另一个类中访问一个类的成员函数
How do you access the member functions of a class within another class?
假设我有一个文件,例如:
//stuff.h
class outer
{
public:
print_inner();
private:
class inner
{
public:
inner(int stuff){
//code
}
};
};
如果我想访问main中的函数inner(int stuff),我会使用以下几行吗?
//stuff.cpp
include "stuff.h"
outer::print_inner(){
int a = 4;
inner* temp = new inner;
temp.inner(a); // is this how we access our inner function?
//some more code
}
您已将class inner
定义为class outer
中的嵌套类。
因此,为了能够在outer
中使用这个类及其成员,首先需要inner
类的对象。您的代码几乎是正确的。
执行任一操作:
outer::print_inner(){
int a = 4;
inner* temp = new inner; // pointer to a dynamicly created object
temp->inner(a); // POINTER INDIRECTION
... // but don't forget to delete temp when you don't need it anymore
}
或
outer::print_inner(){
int a = 4;
inner temp; // create a local object
temp.inner(a); // call its member function as usual.
}
顺便说一下,如果print_innner()
不应该返回值,那么应该将其声明为void
。
在您的特定示例中,inner
是一个构造函数,而不是一个函数,如果您使用指针,则需要使用->
语法。此外,print_inner
需要返回类型。例如,
class outer
{
public:
void print_inner();
private:
class inner
{
public:
void func(int stuff){
//code
}
};
};
outer::print_inner(){
int a = 4;
inner* temp = new inner;
temp->func(a);
//some more code
}
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何仅为一个函数添加延迟
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我需要将多个函数组合为一个函数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 将 N-arg 函数包装到另一个函数中
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- C++从另一个函数退出函数
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 视觉我希望一个函数在另一个函数C++中进行计算
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在另一个函数 (c++) 中调用变量
- 如何在另一个函数中使用返回值作为参数?
- 如何包装一个函数以适应另一个函数的所需类型
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针