你能帮我解决一下Visual C ++中的这些错误吗?我是C ++的新手,我从NetBeans导入了这段代码(设计模式工厂)。在NetBeans中,此代码是正确的。但现在我需要在Microsoft Visual Studio 2010中编译此代码,而我正在生成这些错误:
Creator.h
#pragma once
#include "stdafx.h"
class Creator
{
public:
Product* createObject(int month);
private:
};
错误:
Creator.cpp
#include "stdafx.h"
Product* Creator::createObject(int month) {
if (month >= 5 && month <= 9) {
ProductA p1;
return &p1;
} else {
ProductB p2;
return &p2;
}
}
错误:
IntelliSense:声明与“ Creator :: createObject(int mesic)”不兼容(在第9行声明 - 这是:产品 createObject(int month);)
stdafx.h中:
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>
using namespace std;
#include "Creator.h"
#include "Product.h"
#include "ProductA.h"
#include "ProductB.h"
Product.h:
#pragma once
#include "stdafx.h"
class Product
{
public:
virtual string zemePuvodu() = 0;
Product(void);
~Product(void);
};
Product.cpp:
它只有:
#include "stdafx.h"
Product::Product(void)
{
}
Product::~Product(void)
{
}
谢谢你的回答。
答案 0 :(得分:1)
在
class Creator
{
public:
Product* createObject(int month);
private:
};
您未指定任何private
成员。至少定义一个,或删除private:
:
class Creator
{
public:
Product* createObject(int month);
};
在
Product* Creator::createObject(int month) {
if (month >= 5 && month <= 9) {
ProductA p1;
return &p1;
} else {
ProductB p2;
return &p2;
}
}
当您返回本地对象的地址时,您将创建未定义的行为。
该错误表示您声明返回Product
,但实际上您正在返回指向Product
的指针。你有没有在这里复制和粘贴错误的东西?
确保您的声明
Product* createObject(int month);
符合您的定义
Product* Creator::createObject(int month) { ... }
我无法从这里发现错误...
修改强>
查看代码后,我发现了以下错误:
stdafx.h
被太多包括“中毒”了,特别是using namespace std;
- 声明,绝对没有!ProductA
和ProductB
定义构造函数,结果证明是另一个错误void
作为方法/函数的参数,这是C
- style 虽然这可能听起来像是额外的工作,但是尽量不要将namespace std
引入全局命名空间 - &gt;避免using namespace std;
,特别是在头文件中!
如果没有特别的理由创建带有预编译头文件的项目(stdafx.h
和targetver.h
,请不要这样做,因为它会使事情变得复杂!)
我设法构建了您的项目,但使用的是Visual Studio 2012 Express。如果您无法从我的上传中重新编译项目,请查看源文件并复制内容。
我已将解决方案上传到我的SkyDrive帐户。
如果这有帮助,请接受答案。