嘿,我正在尝试创建一个c ++ stomp客户端, 我的客户端构造函数是:
Client(std::string &server, short port, std::string &login, std::string &pass, Listener &listener);
它获取一个侦听器对象,当Listener是以下接口时:
class Listener {
virtual void message(StmpMessage message) =0;
};
现在我尝试在测试类中实例化一个客户端:
class test : public virtual Listener {
public:
void message(StmpMessage message) {
message.prettyPrint();
}
int main(int argc, char* argv[])
{
Client client("127.0.0.1", 61613, *this);
return 0;
}
};
我将此发送给客户端,因为这是一个侦听器对象, 我收到以下错误:
/Users/mzruya/Documents/STOMPCPP/main.cpp:18: error: no matching function for call to 'Client::Client(const char [10], int, test&)'
/Users/mzruya/Documents/STOMPCPP/Client.h:43: note: candidates are: Client::Client(std::string&, short int, std::string&, std::string&, Listener&)
/Users/mzruya/Documents/STOMPCPP/Client.h:37: note: Client::Client(const Client&)
答案 0 :(得分:2)
它不起作用,因为您将错误的参数传递给Client
c'tor ......
Client(std::string &server, short port, std::string &login, std::string &pass, Listener &listener);
你称之为
Client client("127.0.0.1", 61613, *this);
...您错过了pass
和login
参数。你的听众很好。问题是不与继承有关。
答案 1 :(得分:0)
您的代码出了问题
首先,afaik你无法定义一个类里面的主要内容。该程序在我的电脑上编译(使用gcc),但它会抛出
_start':(.text+0x18): undefined reference to main'
其次,正如Alexander在帖子中所说,你没有在构造函数中传递正确数量的参数来获取这些错误。
第三,在构造函数上传递参数的方式是错误的。引用需要lvalue
。如果要向它们发送rvalue
,则需要将构造函数参数定义为
Client(const std::string &server, short port, const std::string &login, const std::string &pass)
Stroustup的书指出这将被解释为
std::string temp = std::string("127.0.0.1");
server = temp;
简单地说 - 将创建一个临时对象以满足参考。
如您所见,我删除了Listener &listener
参数因为我不知道(并且我认为不是这样),如果您可以将this
作为参数传递。也许有人可以澄清 - 修复它。
如果你想在构造函数中将你的参数作为字符串传递(例如Client("127.0.0.1" , ...)
),那么我想你必须做类似的事情:
std::string hostname = "127.0.0.1";
std::string log = "UserName";
std::string pw = "PassWord";
Client client(hostname, 61613, log , pw);
当然将您的构造函数定义为
Client(std::string &server, short port, std::string &login, std::string &pass)
{
}
也许有人可以澄清this
内容发生的事情,以及你是否以及如何做到这一点。
修改强>
这是我在电脑中用来提出所有这些的代码。希望没关系。
#include <iostream>
//Ghost Class
class StmpMessage
{
public:
void prettyPrint()
{
}
};
class Listener
{
virtual void message(StmpMessage message) = 0;
};
class Client : public virtual Listener
{
public:
Client(std::string &server, short port,
std::string &login, std::string &pass)
{
}
void message(StmpMessage message)
{
message.prettyPrint();
}
};
int main(int argc, char* argv[])
{
std::string hostname = "127.0.0.1";
std::string log = "UserName";
std::string pw = "PassWord";
Client client(hostname, 61613, log , pw);
return 0;
}