[英]How to access nested class member function from enclosing class where all the members are public in c++?
I am using nested classes in a sensor library development and running into errors.我在传感器库开发中使用嵌套类并遇到错误。 Below is sample code and explanation.
下面是示例代码和解释。
MainClass.cpp主类.cpp
class MainClass
{
public:
class nested_class;
void func1(){
nested_class1.print();
}
};
NestedClass.cpp嵌套类.cpp
class MainClass::nested_class
{
public:
virtual void print() = 0;
};
Nested1.cpp嵌套1.cpp
class nested_class1: virtual public MainClass::nested_class{
public:
void print();
};
void nested_class1::print(){
cout<<"This is for 1\n";
}
Nested2.cpp嵌套2.cpp
class nested_class2 : virtual public MainClass::nested_class{
public:
void print(){
cout<<"This is for 2";
}
};
I am trying to use it to extend the concept of abstraction in my sensor library.我正在尝试使用它来扩展我的传感器库中的抽象概念。 But on doing so following is the error: print() was not declared in this scope .
但是这样做会出现以下错误:此 scope 中未声明 print() 。
I am newbie to this concept and hence having a hard time finding the issue here.我是这个概念的新手,因此很难在这里找到问题。 Where am I going wrong here?
我在哪里错了? I can provide more details if required.
如果需要,我可以提供更多详细信息。
Thanks in advance!提前致谢!
nested_class1.print();
isn't how you'd call the print
member of an instance of nested_class1
, even if it were declared before there.不是你如何调用
nested_class1
实例的print
成员,即使它是在此之前声明的。
The definition of MainClass::func1
must be after the definition of nested_class1
, which must be after the definition of MainClass::nested_class
. MainClass::func1
的定义必须在nested_class1
的定义之后,它必须在MainClass::nested_class
的定义之后。
#include <iostream>
class MainClass
{
public:
class nested_class;
void func1();
};
class MainClass::nested_class
{
public:
virtual void print() = 0;
};
class nested_class1: virtual public MainClass::nested_class{
public:
void print();
};
class nested_class2 : virtual public MainClass::nested_class{
public:
void print();
};
void MainClass::func1() {
nested_class1 obj;
obj.print();
}
void nested_class1::print(){
std::cout<<"This is for 1\n";
}
void nested_class1::print(){
std::cout<<"This is for 2";
}
int main(){
MainClass instance;
instance.func1();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.