所以我被困在我认为很容易的事情上。
注意:以下所有内容均适用于 C++11 及更高版本。
让我们开始吧。我有一个名为“员工”的班级。其构造函数如下:
Employee::Employee(const string& first, const string& last, const string& ssn)
: firstName(first), lastName(last), socialSecurityNumber(ssn) {}
此外,在尝试创建对象时,在我的主要内容中,我执行以下操作:
void main()
{
string firstName;
string lastName;
string socialSec;
Employee salariedEmployee{firstName, lastName, socialSec};
}
我得到错误:
错误:无法将变量“salariedEmployee”声明为抽象类型“Employee”
然后我尝试将我的对象创建为指针,如下所示:
Employee *salariedEmployee{&firstName, &lastName, &socialSec};
并得到错误:
错误:标量对象“salariedEmployee”需要初始值设定项中的一个元素
我不明白我做错了什么。我习惯于编码是 C++11 的以前版本,但我正在尝试学习这些使用花括号(统一初始化)的新技巧。我做错了什么(在这两种情况下)?
PS我用谷歌搜索了很多,但我很困惑该怎么做。我保存的两个资源是这些(但已经阅读了更多的东西):
错误:无法将变量“salariedEmployee”声明为抽象类型“Employee”
此错误与您调用构造函数的方式无关。它只是说您正在尝试实例化尚未完全定义的类型,其中一些方法是纯虚拟的。
例如,这有效:
#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};
}
但是如果向 中添加纯虚fire
方法Employee
,它将无法编译:demo。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句