Defining structure types in a class



  • Pardon me if this is a dumb question but this is driving me nuts. I want to define a structure as a private class member and have a class function return that structure after I fill it with some data values but when I try to implement the darn thing (simple example) as follows:

    atest.h
    @class aTEST
    {
    struct myTest {
    int a;
    int b;
    };
    mytest ck;
    myTest test();
    public:
    aTEST();
    };@

    atest.cpp
    @#include "atest.h"
    aTEST::aTEST()
    {
    myTest bk;
    bk.a = 1;
    bk.b = 1;
    ck.a = 0;
    ck.b = 0;
    }
    myTest aTEST::test(){
    myTest temp;
    temp.a = 0;
    temp.b = 0;
    return temp;
    }@

    I get compiler errors that myTest is not a type for the atest function in the cpp and that ck is not defined in the constructor.

    The ck error is strange to me because if I change

    @ struct myTest {
    int a;
    int b;
    };
    mytest ck;@
    to
    @ struct myTest {
    int a;
    int b;
    }ck; @

    it compiles okay with respect to ck. I don't see why it compiles for this change but not for the original.

    But the basic problem is why the compiler doesn't recognize myTest as a type for functions. In the constructor myTest is recognized as a type for bk by the compiler. I though maybe it was a scope problem so moved the structure definition to outside the class definition (i.e., above the class declaration) but it still didn't compile (I also tried various other combinations but cannot seem to get it to work).

    So the question is how can you define a class function that returns a structure? Is it possible?



  • I tested your code, and I found two issues:
    @
    class aTEST
    {
    struct myTest {
    int a;
    int b;
    };
    // typo in type name
    // mytest ck;
    myTest ck;
    myTest test();
    public:
    aTEST();
    };
    @

    @
    // myTest is in aTest so this is wrong
    // myTest aTEST::test(){
    aTEST::myTest aTEST::test(){
    myTest temp;
    temp.a = 0;
    temp.b = 0;
    return temp;
    }
    @

    I compiled it under g++ 4.6.1.



  • Thanks. I thought it was a scope problem but my typo masked my test results. It's always the little things!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.