【发布时间】:2019-06-20 12:27:08
【问题描述】:
在我的 C++ 类中,我有两个静态方法,称为 getInstance。
方法声明如下:
public: // +++ STATIC +++
static CanCommunicator* getInstance(shared_ptr<ThreadState> state);
static CanCommunicator* getInstance();
在一个全局函数中(需要,因为遗留代码),我从对象中调用一个 getter:
auto tState = CanCommunicator::getInstance()->getThreadState();
编译器 (GCC 4.4.5) 出现以下错误:
CanCommunicator::getInstance is ambiguous
Candidates are:
CanCommunicator * getInstance()
CanCommunicator * getInstance(std::shared_ptr<IsoTpThreadState>)
是什么导致了这个错误,我该如何解决? 实例创建需要重载的方法,不带参数的方法用于纯实例检索。
编辑:根据请求为示例提供更多代码。
#include <memory>
#include <stdint.h>
#include <linux/can.h>
#include <linux/can/raw.h>
using std::shared_ptr;
//================
// Class in question
//================
struct ThreadState {
int32_t socketFd;
uint32_t sendId;
};
class CanCommunicator {
#define null NULL
public: // +++ STATIC +++
static CanCommunicator* getInstance(shared_ptr<ThreadState> state);
static CanCommunicator* getInstance();
public:
shared_ptr<ThreadState> getThreadState() { return this->threadState; }
protected:
CanCommunicator(shared_ptr<ThreadState> state);
private: // +++ STATIC +++
static CanCommunicator* instance;
private:
shared_ptr<ThreadState> threadState;
};
/*
+++++++++++++++++++++++++++++++++++++
+++ STATIC VARIABLES +++
+++++++++++++++++++++++++++++++++++++
*/
CanCommunicator* CanCommunicator::instance = null;
/*
+++++++++++++++++++++++++++++++++++++
+++ STATIC METHODS +++
+++++++++++++++++++++++++++++++++++++
*/
CanCommunicator* CanCommunicator::getInstance(shared_ptr<ThreadState> state) {
if (state == null && instance == null)
throw "Cannot instantiate from nullptr!";
return instance == null ? (instance = new CanCommunicator(state)) : instance;
}
CanCommunicator* CanCommunicator::getInstance() { return instance == null ? throw "No instance found!" : instance; }
CanCommunicator::CanCommunicator(shared_ptr<ThreadState> state) {
this->threadState = state;
}
//================
// Calling code
//================
int canSendData(int32_t skt, uint32_t sendCanId, const uint8_t* data, uint8_t dataLength, uint8_t extended) {
struct can_frame myCanFrame;
return (int)write(skt, &myCanFrame, sizeof(myCanFrame));
}
int isotp_user_send_can(const uint32_t arbitrationId, const uint8_t* data, const uint8_t size) {
auto tState = CanCommunicator::getInstance()->getThreadState(); //<-------- Error originates here
return canSendData(tState->socketFd, (int)tState->sendId, data, size, false) > 0 ? 0 : 1;
}
【问题讨论】:
-
发布的代码不应产生此错误。请给我们一个minimal reproducible example 好吗?
-
提供的代码(缺少功能)可以工作here。
-
这并没有解决问题,但是从
getInstance(shared_ptr<ThreadState>)返回的三元运算符很难阅读。分手吧:if (instance == null) instance = new CanCommunicator(state); return instance;. -
也许将违规的
getInstance(std::shared_ptr<IsoTpThreadState>)重命名为 - 例如 -getInstanceByState(std::shared_ptr<IsoTpThreadState>)?
标签: c++ oop static-functions