How to instatiate a class from another class in Qt C++
I had made 2 class in my project. I want to use a function from 1st class to the 2nd class the problem is I can't instantiate the 1st class to the 2nd class. By the way both classes were declared in different headers.
here is a sample code:
header 1:
class 1stclass{
public:
2ndclass *class2;
void function1(QString parameter1)
{
QString str1;
list = class2->function2(parameter1);
}
};
header 2:
class 2ndclass{
public:
QString function2(QString parameter2)
{
QString str2 = parameter2 + "hello";
return str2;
}
};
I want to use the function in function 2 but it gives me an error. here is the error message:
- ISO C++ forbids declaration of '2nd开发者_如何学Goclass' with no type;
- expected ';' before '*' token;
- 'class2' was not declared in this scope;
Class names aren't allowed to start with a number in C++.
Class1
and Class2
are valid names though.
The compiler does not know anything about the second class when trying to create the pointer. Didn't you forget to include the header file with the second class declaration? Is the file included in your qt project file or Makefile? By the way, the first character of an indetifier can't be a number, only a-z and underscore.
Why don't you use a .cpp file. The first class can't know what 2ndclass is unless you include the header.
Header 2:
class SecondClass
{
public:
QString function2( const QString ¶meter2 );
};
Cpp 2:
SecondClass::function2( const QString ¶meter2 )
{
// your func
}
Header 1: You can include header2.h or use a forward declaration like
class SecondClass;
class FirstClass
{
public:
QString function( const QString ¶meter );
SecondClass *s2;
};
Cpp 1:
#include "SecondClass.h"
FirstClass::function( const QString ¶meter )
{
s2 = new SecondClass;
QString str1;
list = s2->function2(parameter1);
}
精彩评论