假设我有一个文件,例如:
//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
}
答案 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
。