return a string by ref

C

cpp

I have the following code

class A
{
private:
string s1;
string s2;
string s3;
string s4;

// Need a function f1 which returns one of the 4 strings based on

public:
A()
{
// initialize s1, s2, s3, s4
}

void f2()
{
// will use s1, s2, s3 based on the value returned by f1
// will not modify the string
}

};

What should be the signature of f1?

do any of the following look like the right thing to use
string & f1() ;
const string & f1();
 
L

lallous

Hello

Your question is not clear.

It is better to create the strings as an array as:

string s[4]

Then f1() returns a const reference to any of s[0] to s[3] depending on some
condition

Say,
const string &f1(int idx)
{
// idx bounds checks here
return s[idx];
}

HTH
Elias
 
A

Andrey Tarasevich

cpp said:
I have the following code

class A
{
private:
string s1;
string s2;
string s3;
string s4;

// Need a function f1 which returns one of the 4 strings based on

Based on what?
public:
A()
{
// initialize s1, s2, s3, s4
}

void f2()
{
// will use s1, s2, s3 based on the value returned by f1
// will not modify the string
}

};

What should be the signature of f1?

do any of the following look like the right thing to use
string & f1() ;
const string & f1();

It depends on what you need. If you want 'f1' to explicitly restrict the
calling code from modifying the strings, then you use the second
variant. Or, even better, 'const string & f1() const'. This will also be
callable from 'const' member functions. The first variant is not.
 
F

Frederick Gotham

cpp posted:
class A
{
private:
string s1;
string s2;
string s3;
string s4;

// Need a function f1 which returns one of the 4 strings based on


string const &f1(unsigned const i) const
{
assert(i <= 4);

switch (i)
{
case 1: return s1;
case 2: return s2;
case 3: return s3;
case 4: return s4;
}
}

string &f1(unsigned const i)
{
return const_cast<string&>( static_cast<A const*>(this)->f1(i) );
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top