如何在另一个类中访问一个类的成员函数

How do you access the member functions of a class within another class?

本文关键字:一个 函数 成员 另一个 访问      更新时间:2023-10-16

假设我有一个文件,例如:

//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
}