Hello again.
Once again another problem...
Well i made a very good string class, only problem is, i don't know how to use an operator= for assignment.
I have operator='s programed in but i don't know how to make it an assignment operator.
for instance:

String str1 = "Hello"; // what i want it to do
String str2("Hello"); // what it does now...

how would i put that in code? would i make the constructor:
String operator=?

if i try to do it now with the = operator, it says no matching function.
instead i have to do this:

String str;
str = "Hello";

and one more question...
i want to add operator+(...) but, im not sure how to assign it, i know i need to make it a return value of String, or char*. But how do i do it? do i have to do:

String operator+(String,char*);
String operator+(String,int);
// ect..
String operator+(char*,char*);
String operator+(char*,int);
// ect...

or is there a shorter way like a "..." operator

Thanks in advance. :)

8 Years
Discussion Span
Last Post by u8sand

Like MyStringClass object = const char *; ?
You'd just simply overload it.

overload it in what way? can i have an example please?


Im not sure u completly understood what i was asking. I want to know how to overload the = operator when you assign the string. I already have it overloaded, but it doesent work when i try and assign it like so:

// works:
String str;
str = "Hello";
// Does not work: (but i want to work)
String str = "Hello";

how would i go about doing that.
its like when you define an integer:

// like this:
int i = 0;
// you dont have to do this:
int i;
i = 0;

What does the default constructor look like (the one with no arguments). That could be causing a problem. Please post more specific code (the actual class perhaps?) and the incorrect result you are getting (error message? wrong output?). It is good c++ practice to always initialize an object with its constructor, and not with an assignment. But that's subjective and a properly written operator=() should still work for you.


String s = "anything" is not an assignment, it's initialization!
So you must define a proper constructor:

class String {
    String(const char*);
String s = "This constructor called!";
String t("The same constructor called!");

I know how to make a constructor.
When i try to define it with the = operator it says:
No matching function call for String(String)
when i make a constructor with string i need to use String&... or i get an error.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.