编译器似乎不接受Agent类

时间:2009-11-18 16:16:02

标签: c++ class namespaces

可能答案很愚蠢,但如果你愿意,我需要一双新鲜的眼睛来发现问题。这是_tmain:

的摘录
Agent theAgent(void);
int m = theAgent.loadSAG();

这是agent.h,我包含在_tmain:

#ifndef AGENT_H
#define AGENT_H
class Agent {
public:
Agent(void);
int loadSAG(void);
~Agent(void);
};
#endif

和agent.cpp相关功能:

int Agent::loadSAG(void) {
return 3;
}

所以为什么在世界上我得到这个错误:错误C2228:'。loadSAG'的左边必须有class / struct / union?

提前致谢。

6 个答案:

答案 0 :(得分:7)

Agent theAgent(void);

这是一个函数声明,只需将其更改为:

Agent theAgent;

答案 1 :(得分:4)

编译器认为

Agent theAgent(void);

这是一个功能声明。

Agent theAgent;

答案 2 :(得分:3)

该行

Agent theAgent(void);

编译器实际上将其视为声明函数theAgent,该函数不带参数并返回代理。

C++ FAQ Lite解释了这一点。

要调用默认构造函数并设置类型为Agent的对象(与上面被解释为函数声明的语句相反),您只需声明theAgent而不使用括号,如:

Agent theAgent;

此后,所有正常的成员呼叫(例如loadSAG)都将按预期工作。

作为替代方案,如果您必须在堆上拥有该对象,请改为使用:

Agent* theAgent = new Agent();  // Notice the *
theAgent->loadSAG();            // Use -> instead of .

// The code where theAgent is used

delete theAgent;  // This frees the memory allocated by new

答案 3 :(得分:1)

如果通过 Agent theAgent(void); 你的意思是函数声明然后你可能忘了将()添加到函数调用

int m = theAgent().loadSAG();

如果您想要定义名为theAgent的变量,那么您已添加了额外的(void)。 而你应该写

Agent theAgent;

答案 4 :(得分:1)

调用默认(无参数)构造函数时,不使用'()'。 IE浏览器。尝试构建代理对象:

Agent theAgent;

答案 5 :(得分:-3)

Agent theAgent = new Agent();
theAgent.loadSAG();

在尝试使用代理对象之前,错误消息似乎从未实例化过。