Initialize an object with an equal operator

In the class below named foo

class foo{
private:
    string str;
public:
    foo operator = (string s){
         str = s;
    }
};

int main(){
    foo a = "this initialization throwing an error";
    foo b;
    b = "but assignment after declaration is working fine";
}

error: conversion from 'const char [38]' to non-scalar type 'foo' requested

The above error only occurs when I assign a value to an instance of an object with a declaration, but if I assign it separately from the declaration, then the overloaded equal =operator works fine.

I want in any method to assign a string to an object with an equal operator and as an declaration , for examplefoo a = "abcd";

+4
source share
5 answers

If you

type name = something;

, - ( , ). , , =.

, std::string, const char* const char[], .

, , ,

b = "but assignment after declaration is working fine";

-, , ,

"but assignment after declaration is working fine"

std::string.

, cstring,

foo(const char* str) : str(str) {}
+4

:

, =, - . .

. :

, std::string:

foo( const std::string &s );

foo :

foo f( "abc" );

:

foo f = foo( "abc" );

-:

, , , , .

, ctor:

 foo( const char *str );

: ctor, - . foo.

+2

,

foo a = "initialization string";

foo, , .

:

foo(const std::string& s) : str(s) {}
foo(const char* s) : str(s) {}
+1

, , =:

struct S {
    S(int);
};

S s = 3; // initialization, not assignment

S(int) S, S .

, :

S s1;
s1 = 3; // assignment

, S . b = .

+1

, ,

class foo{
private:
    string str;
public:
    foo operator = (string s){
         str = s;
    }
};

, , foo.

,

    foo & operator = ( const std::string &s){
         str = s;
         return *this;
    }

, , .

, . ,

foo();

,

for( const foo & );

foo a = "this initialization throwing an error";

, foo, a. . foo. , , .

error: 'const char [38]' 'foo'

const char[33] - .

foo b;
b = "but assignment after declaration is working fine";

b foo, , , . , str std::string, . , std::string .

+1

Source: https://habr.com/ru/post/1660987/


All Articles