调用struct类构造函数

Call constructor for struct class

本文关键字:构造函数 struct 调用      更新时间:2023-10-16
namespace CommunicatorApi
{
    class ApiObserver;
    class COMM_API_EXPORT Api
    {
        public:
            //! Basic constructor
            Api(ApiObserver& observer);
            //! Destructs the object and frees resources allocated by it
            ~Api();
    }
}

我试图致电

#include <iostream>  
#include "include/communicator_api.h"  
using namespace std;  
int main()  
{  
    cout << "Hello, world, from Visual C++!" << endl;
    CommunicatorApi::Api::Api();
} 

但是我正在收到错误

CommunicatorApi::Api::Api no approprate default constructor available

您已经定义了具有参数的构造函数,因此未生成默认构造函数。自动生成默认/复制/移动CTOR和复制/移动分配操作员的条件?

,因为您的形式具有自定义定义的构造函数:

        Api(ApiObserver& observer);

除非您也明确定义它,否则您不得使用默认构造函数。

您可以使用以下方法之一来解决问题。

选项1:定义默认构造函数

class COMM_API_EXPORT Api
{
    public:
        //! Default constructor
        Api();
        //! Basic constructor
        Api(ApiObserver& observer);
        //! Destructs the object and frees resources allocated by it
        ~Api();
}

然后,您可以使用:

CommunicatorApi::Api::Api();

选项2:使用自定义构造函数

CommunicatorApi::ApiObserver observer;
CommunicatorApi::Api::Api(observer);

ps

CommunicatorApi::Api::Api(observer);

创建一个临时对象。您可能想拥有以后可以使用的对象。为此,您需要:

CommunicatorApi::Api apiObject(observer);