Colleagues,

The program written in class is not compiled.

#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> using namespace cv; using namespace std; class Person { int age; string name; string surname; public: void dataChange (int y, string m_name, string m_surname) { age=y; name=m_name; surname=m_surname; } void print() { cout<< "My name is "<<name<<" "<<surname<<" and I am "<<age<< " years old"<<endl; } }; int main() { Person me = ( 28, "Stepan", "Sokol"); me.print(); me.dataChange(27, "Esteban", "Falke"); me.print(); getchar(); return 0; } 

There are errors on the line of declaration of the Person class me variable:

Error 1 error C2440: 'initializing': cannot convert from 'const char [6]' to 'Person' c: \ users \ u20y36 \ desktop \ progs \ project2 \ project2 \ source.cpp 32 1 Project2

2 IntelliSense: no "const char [6]" to "Person" c: \ Users \ u20y36 \ Desktop \ Progs \ Project2 \ Project2 \ Source.cpp 32 14 Project2

What is the problem? Thank you.

    2 answers 2

    You have some strange lines

     Person me = ( 28, "Stepan", "Sokol"); me.print(); me.dataChange(27, "Esteban", "Falke"); me.print(); 

    Most likely implied

     Person me; me.dataChange(28, "Stepan", "Sokol"); me.print(); me.dataChange(27, "Esteban", "Falke"); me.print(); 

    initialization is immediately possible if you implement a constructor with arguments

     public: Person(int age, string name, string surname) { this.age=age; this.name=name; this.surname=surname; } 

    Then you can write

     Person me(28, "Stepan", "Sokol"); 
    • Earned without new Person (). But can't I initialize me right away? - Stepan Sokol
    • You probably confused the language, in c ++ Person me = new Person(); will cause a compilation error. - VTT
    • @VTT, yes, exactly - Komdosh
    • Thank you What you need - Stepan Sokol

    To initialize an object, define the appropriate constructor:

     public: explicit Person(int const initial_age, char const * const psz_name, char const * const psz_surname) : age{initial_age}, name{psz_name}, surname{psz_surname} {} 

    then it can be called like this:

     Person me{28, "Stepan", "Sokol"}; 
    • Thank you What you need - Stepan Sokol