简体   繁体   中英

C++ function with a struct vector as a return value

I want to create a private function in C++ (VS2010). It should return a vector/array of structs/userdefined type.

However I think my declaration of the function in the cpp file is perhaps wrong. Or maybe already in the header. Can somebody have a look at it?

My header looks like this:

#pragma once
using namespace std;
#include <algorithm>
#include <vector>
class clsWString2
{
private:
struct udtWChar2
{
    wstring Text;
    int OrigPos;
};
bool m_bDirty;
vector<udtWChar2>pToWChar2(wstring u);

vector<udtWChar2>m;
public:
clsWString2(void);
~clsWString2(void);
void ReplaceCompareBinary(wstring uSearchFor, wstring uReplaceBy);
void ReplaceCompareText(wstring uSearchFor,wstring uReplaceBy);
void ReplaceByPos(int uStartPos1Based,int uLen0Based, wstring uReplaceBy);
void FeedString(wstring u);
void Append(wstring u);
wstring CharAtPos(int uIndex);
int OrigPos(int uIndex);
};

And my .cpp file looks like this:

#include "StdAfx.h"
#include "clsWString2.h"


clsWString2::clsWString2(void)
{
m.resize(0);
}
clsWString2::~clsWString2(void)
{
}
vector<udtWChar2> clsWString2::pToWChar2(wstring u)
{
vector<udtWChar2> n;
n.resize(0);

for (int i=0;i<u.size();i++)
{

    wstring sChar;
    sChar=u.substr(i,1);

    udtWChar2 nc;
    nc.Text =sChar;
    nc.OrigPos=i;

    n.push_back (nc);
}

return n;
}

In the source file, when you define the function, the return type is not in the scope of the class so the class in the vector needs to be fully qualified:

vector<clsWString2::udtWChar2> clsWString2::pToWChar2(wstring u)
{
    ...
}

啊,我明白了:

vector<clsWString2::udtWChar2> clsWString2::pToWChar2(wstring u)

You can not use directly udtWChar2 as type , you need define type def or you need use as struct udtWChar2

Like :

in .h

vector  < struct udtWChar2 > pToWChar2(wstring u);
vector  < struct udtWChar2 > m;

in .cpp

vector < struct clsWString2::udtWChar2 > clsWString2::pToWChar2(wstring u)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM