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

时间:2015-02-24 23:30:00

标签: c++

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

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

2 个答案:

答案 0 :(得分:2)

在您的具体示例中,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
}

答案 1 :(得分:2)

您已在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