嘿,我正在尝试创建一个c++ stomp客户端,我的客户端构造函数是:
Client(std::string &server, short port, std::string &login, std::string &pass, Listener &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&)发布于 2010-12-24 22:14:56
它不起作用,因为您向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参数。你的听众很好。这个问题与继承无关。
发布于 2010-12-24 23:17:21
您的代码中有一些错误
首先,afaik你不能在一个类中定义main。程序在我的pc上编译(使用的是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;简单地说,将创建一个temp对象来满足引用。
正如你所看到的,我去掉了Listener &listener参数,因为,我不知道(和tbh,我不认为),如果你可以把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的事情发生了什么,以及你是否可以以及如何做到这一点。
编辑:
这是我在我的pc中使用的代码,用来实现所有这些。希望它是好的。
#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;
}https://stackoverflow.com/questions/4526769
复制相似问题