简体   繁体   中英

Initializing object and pointer object using uniform initialization does not work

so I am stuck at something that I think is easy.

Note: everything below is for C++11 and above.


Let us start. I have a class named "Employee". Its consctructor is as follows:

Employee::Employee(const string& first, const string& last, const string& ssn)
      : firstName(first), lastName(last), socialSecurityNumber(ssn) {}

Furthermore, when trying to create the object, in my main, I do the following:

void main()
{
string firstName;
string lastName;
string socialSec;
Employee salariedEmployee{firstName, lastName, socialSec};
}

and I get the error:

error: cannot declare variable 'salariedEmployee' to be of abstract type 'Employee'


then I tried to create my object as a pointer, as followes:

Employee *salariedEmployee{&firstName, &lastName, &socialSec};

and get the error:

error: scalar object 'salariedEmployee' requires one element in initializer


I do not understand what I am doing wrong. I was used to coding is previous versions of C++11 but I am trying to learn these new tricks of using curly braces (uniform initialization). What am I doing wrong (in both cases)?

PS I have googled a lot but I am very confused about what to do. Two of the resourses I saved are these (but have read much more stuff):

error: cannot declare variable 'salariedEmployee' to be of abstract type 'Employee'

This error is not related to the way you call your constructor. It just says you are trying to instantiate a type which has not been completely defined, some of its methods are pure virtuals.

For instance, this works:

#include <string>

struct Employee
{
    Employee(const std::string& first, const std::string& last, const std::string& ssn);

    std::string firstName;
    std::string lastName;
    std::string socialSecurityNumber;
};

Employee::Employee(const std::string& first, const std::string& last, const std::string& ssn)
    : firstName(first), lastName(last), socialSecurityNumber(ssn)
{}

int main()
{
    std::string firstName;
    std::string lastName;
    std::string socialSec;
    Employee bob{firstName, lastName, socialSec};
}

demo

But if you add a pure virtual fire method to Employee , it will fail to compile: demo .

Although it works fine on my computer. In your case the problem can be the uniform initialization . Basically, the constructor is aa special kind of class Method (function, sort-of).

So, the way to pass arguments to a function is by parentheses () ,not by uniform initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM