N
N
nik1202952015-10-12 20:41:40
C++ / C#
nik120295, 2015-10-12 20:41:40

Why does the "cpy" function work with strings?

There was a silly question "WHY DOES IT WORK?".
So this is why the "cpy" function works both with a class object
a.cpy(b).print();
and with a simple string

a.cpy(ca).print();
    a.cpy("rap").print();

?
If she accepts
String &String::cpy(const String& a){}
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;

class String
{
public:
    String();//конструктор по умолчанию
    String(const String &st);//конструктор глубого копирования
    String(const char *str);//конструктор по принимаемой строке
    ~String();//деструктор
    //int length() const;//функция возврата длины строки
    String& cpy(const String& a);//функция копирования а в строку
    //String& cat(const String& b);//функция сцепления строки b и  строки
    //int cmp(const String& c)const;//функция проверки строк на эквивалентность
    //String& str(const String& a, const String& b);//поиск подстроки b в а
    void print() const;//функция вывода строки в консоль
private:
    int len;//длина строки
    char *s;//строка
};
String::String()//конструктор по умолчанию
{
    len=1;//длине строки присваеваем 1
    s=new char[len];//выделяем память для строки s динной l
    s[0]='\0';//записываем пустую строку
}

String::String(const char *str)//конструктор по принимаемой строке
{
    len=strlen(str)+1;//длине строки присваеваем длину входящей строки +1
    s=new char[len];//выделяем память для строки s динной len
    strcpy(s,str);//копируем вдящую строку в строку s
}

String::String(const String& st)//конструктор глубого копирования
{
    len=st.len;//длине строки присваеваем длину входящей строки
    s=new char[len];//выделяем память для строки s динной len
    strcpy(s,st.s);//копируем вдящую строку в строку s
}

String::~String()//деструктор
{
    delete []s;//удаляем s
}

int String::length()const//функция возврата длины строки
{
    return len-1;//возращаем длину строки
}

String &String::cpy(const String& a)//функция копирования а в строку
{
    if(!strcmp(s,a.s))//проверям на эквиваленткность строку s  и входящую строку
        return *this;
    len=a.len;//длине строки присваеваем длину входящей строки
    delete []s;//удаляем строку s
    s=new char[len];//выделяем память для строки s динной len
    strcpy(s,a.s);//копируем входящую строку в строку s
    return *this;
}
void String::print() const//функция вывода строки в консоль
{
    cout<<" "<<s<<" "<<endl;//выводим строку s
}
int main(){
    const char *ca="wety";
    String a("Hello"),b(a);
    a.cpy(b).print();
    a.cpy(ca).print();
    a.cpy("rap").print();
}

Everything works and outputs:
"
er
qwerty
wety
rap
"
but why is "it" so?
Thank you all in advance for your reply!!!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2015-10-12
@nik120295

Make it a rule to make all constructors with one argument explicit (well, there are cases where this can be inconvenient, but good advice for a beginner). In this case there will be no implicit conversions and your code won't compile until you write a.cpy(String("rap")).print().
And I understand everything, but to call the function "cpy"... It makes me want to read it in Russian. This function, purely in meaning, should be replaced with an assignment operator .

S
Stanislav Makarov, 2015-10-12
@Nipheris

String(const char *str);//constructor according to the received string

here is the answer. ( implicit conversion constructor ).
If you want to check - put an explicit keyword before this constructor - and the line
a.cpy("rap").print();

should stop compiling.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question