Using a string as arguement for a constructor

When I try the same but with int instead of string on all places (and 5 instead of "Hej") it works.
1
2
3
4
5
6
7
8
9
10
11
//main.cpp
#include <iostream>
#include<string>
#include "Range.h"

using namespace std;
int main(void)
{
    Range r1((string)"Hej");
    return(0);
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Range.h
#ifndef RANGE_H_INCLUDED
#define RANGE_H_INCLUDED

#include <string>
class Range
{
    public:
        Range();
        Range(string s);
        ~Range();
};

#endif // RANGE_H_INCLUDED 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//Range.cpp
#include <iostream>
#include <string>

using namespace std;

class Range
{
    public:
    Range();
    Range(string s);
    ~Range();

};
Range::Range(){
}

Range::Range(string s){
    cout << "String is: " << s;
}

Range::~Range(){
    //Destuctor
}


I get the error:

Range.h:9: error: expected `)' before "s"
main.cpp: In function `int main()':
main.cpp:10: error: no matching function for call to `Range::Range(std::string)'
Range.h:6: note: candidates are: Range::Range(const Range&)
Range.h:8: note: Range::Range()
Process terminated with status 1 (0 minutes, 0 seconds)
2 errors, 0 warnings
Last edited on
Why dont you use ?
 
string( "Hej" )

You also duplicated the class prototype.

Try this;
1
2
3
4
5
6
7
8
9
10
11
12
//main.cpp
#include <iostream>
#include<string>
#include "Range.h"

using namespace std;

int main(void)
{
    Range r1(string("Hej"));
    return(0);
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Range.h
#ifndef RANGE_H_INCLUDED
#define RANGE_H_INCLUDED

#include <string>
class Range
{
    public:
        Range();
        Range(std::string s);
        ~Range();
};

#endif // RANGE_H_INCLUDED 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Range.cpp
#include <iostream>
#include <string>

using namespace std;

Range::Range(){
}

Range::Range(string s){
    cout << "String is: " << s;
}

Range::~Range(){
    //Destuctor
}
Last edited on
I get the same error message either way. I'm no expert lol, bit isn't just two equivalent ways to typecast? If I remove it all together I get the error:

main.cpp:10: error: no matching function for call to `Range::Range(const char[4])'

instead, so my initial code did change the type. (compared to: main.cpp:10: error: no matching function for call to `Range::Range(std::string)')
Last edited on
Adding "std::" solved it. Man I suck :(!

Thanks
Last edited on
(string)"Hej"
may work but string data type has already a constructor which takes const char* as argument.
I suggest you to use constructors rather than type casts.
may work but string data type has already a constructor which takes const char* as argument.
I suggest you to use constructors rather than type casts.


After ur "std::"-magic it turned out I could skip that part all together. Just "Hej" works fine. Will def follow the advice in the future though.
Topic archived. No new replies allowed.