我有很长时间的Java用户使用Qt学习C++,并且在理解方法的工作方式时遇到了很多麻烦。现在,我正在尝试找出数据库,并尝试使用 header 简化我的代码。通常在Java中,我只有一个名为DatabaseControl的类,该类具有可以执行我想要执行的操作的void方法。例如,像我现在所做的那样,将一个雇员添加到数据库中。我会通过做类似的事情来实例化类(class)
DatabaseControl myDBControl = new DatabaseControl();
然后执行
myDBControl.addEmploye();
这将弹出一系列输入框,供用户输入有关员工的信息-姓名,部门等。
因此,现在转到C++。我有我的 header
class DatabaseControl
{
public:
DatabaseControl();
~DatabaseControl();
//Methods
void addEmployee();
};
我的构造函数中没有任何参数,因为我想要做的就是在主程序中调用“addEmployee”方法,如上所示。在同一个头文件中,我在类声明下面
void DatabaseControl::addEmployee(){
QSqlQuery qry;
bool ok;
QString firstName = QInputDialog::getText(NULL, "QInputDialog::getText()",
"Employee first name:", QLineEdit::Normal,
NULL, &ok);
if (ok && !firstName.isEmpty()){}
else{
QMessageBox msgBox;
msgBox.setWindowTitle("Error");
msgBox.setText("Failed to add employee.\nReason: No employee name given.");
msgBox.exec();
}
QString lastName = QInputDialog::getText(NULL, "QInputDialog::getText()",
"Employee last name:", QLineEdit::Normal,
NULL, &ok);
if (ok && !lastName.isEmpty()){
qry.prepare("INSERT INTO employees (firstname, lastname)" "VALUES (:f1, :f2)");
qry.bindValue(":f1", firstName);
qry.bindValue(":f2", lastName);
qry.exec();
}
else{
QMessageBox msgBox;
msgBox.setWindowTitle("Error");
msgBox.setText("Failed to add employee.\nReason: No employee name given.");
msgBox.exec();
}
}
然后在我的主要我有:
void MainWindow::on_addEmployee_clicked()
{
DatabaseControl myDBControl();
myDBControl.addEmployee();
}
我希望它只运行我在头文件中编写的addEmployee方法。但是,当我编译时,出现错误错误:C2228:“。addEmployee”的左侧必须具有class / struct / union
我查看了该错误的其他实例,但并没有真正确切地了解出什么问题,而且我认为这是由于我对C++中的方法的误解所致,因为我知道在Java中类似的东西可以正常工作(假设代码在 header 是正确的(很可能不是)
最佳答案
您在这里犯了一个错误:
DatabaseControl myDBControl();
您声明了一个名为
myDBControl
的函数,该函数不带任何参数并返回DatabaseControl
。没有任何构造函数参数的对象声明必须省略
()
:DatabaseControl myDBControl;
这与(但不完全是)“most vexing parse”相关,因为它是由相同的语言规则引起的,即如果可以对语句进行解析,则它们就是函数声明。
关于c++ - 错误:C2228: ''的左侧必须具有class/struct/union,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49767804/