读书人

生手疑问为什么这个类编译时显示成员

发布时间: 2013-01-11 11:57:35 作者: rapoo

新手疑问,为什么这个类编译时显示成员函数重复定义
这个类能够编译通过。


#ifndef MYMAINWINDOW_H
#define MYMAINWINDOW_H

#include <QMainWindow>
#include <QAction>

class MyMainWindow : public QMainWindow
{
Q_OBJECT

public:
MyMainWindow(){createActions();}

private:
void createActions(){newAction = new QAction(tr("&New"), this);}
QAction *newAction;


};
#endif // MAINWINDOW_H


而这个却通不过:

#ifndef MYMAINWINDOW_H
#define MYMAINWINDOW_H

#include <QMainWindow>
#include <QAction>

class MyMainWindow : public QMainWindow
{
Q_OBJECT

public:
MyMainWindow();

private:
void createActions();
QAction *newAction;


};

MyMainWindow::MyMainWindow()
{
createActions();
}

void MyMainWindow::createActions()
{
newAction = new QAction(tr("&New"), this);
}

#endif // MAINWINDOW_H


这两个类都符合C++的语法,为什么第二个通不过编译?
[解决办法]
第二个不符合C++语法!
请在函数实现部分前边加上关键字inline
[解决办法]
MyMainWindow::MyMainWindow()
{
createActions();
}

void MyMainWindow::createActions()
{
newAction = new QAction(tr("&New"), this);
}

你重新建一个cpp文件 把上面的那一段放到cpp文件中 就卜会报错啦..
[解决办法]
引用:
感谢二位的解答。

C++中规定声明和实现一定要放在.h和.cpp文件中吗?
如下代码在VS中能编译通过:
C/C++ code

//ClassA.h
#ifndef CLASSA_H
#define CLASSA_H

class ClassA
{
public:
ClassA();
int getN();

private:
int n;
};

Cla……

在Qt中是不能放在一起的。可是按照C++语法,你这样写是没有问题的啊

读书人网 >QT开发

热点推荐