答案可能很明显,但我在这个问题上花了好几个小时没有运气。
我有一个名为" images"的命名空间,其中有一个类" Image"被定义为。标题编译正常,但.cpp遇到问题。
这是标题:
//Image.h
#ifndef _IMAGE
#define _IMAGE
#include "Array.h"
#include "Serializable.h"
#include "Vec3.h"
#include "ppm_format.h"
namespace imaging
{
class Image : math::Array<float>, Serializable
{
public:
math::Vec3<float> * pixels;
// constructors and destructor
Image(); // default: zero dimensions, nullptr for the buffer.
Image(unsigned int w, unsigned int h);
Image(unsigned int w, unsigned int h, const math::Vec3<float> * data_ptr);
Image(const Image &src);
~Image();
Image & operator = (const Image & right);
};
} //namespace imaging
#endif
这里是.cpp。一切运行正常,直到最后一个运算符重载:
//Image.cpp
#include "Image.h"
namespace imaging {
Image::Image() : Array(0, 0), pixels(nullptr) {}
Image::Image(unsigned int w, unsigned int h) : Array(w, h) {}
Image::Image(unsigned int w, unsigned int h, const math::Vec3<float> * data_ptr) : Array(w, h)
{
memcpy(pixels, data_ptr, sizeof(data_ptr));
}
Image::Image(const Image &src) : Array(src.width, src.height), pixels(src.pixels) {}
Image::~Image() {
if (pixels != nullptr) delete[] pixels;
}
Image& Image::operator=(const Image& right) {
memcpy(pixels, right.pixels, sizeof(right.pixels));
return *this;
}
...
}
以下是错误:
error C2143: syntax error: missing ';' before '&'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2086: 'int imaging::Image': redefinition
error C2761: 'imaging::Image &imaging::Image::operator =(const imaging::Image &)': member function redeclaration not allowed
error C2059: syntax error: '{'
error C2143: syntax error: missing ';' before '{'
error C2447: '{': missing function header (old-style formal list?)
error C2509: '<<': member function not declared in 'imaging::Image'
它就像&#34; Image&#34;是一个随机的词。
有什么想法吗?非常感谢!
编辑:BTW,将代码从.cpp转移到头部解决了所有问题。但问题仍然存在,这个例子中的错误是什么?答案 0 :(得分:0)
我在运行您的代码时没有错误,您可以在此处看到: https://ideone.com/NmJOpn
#include <iostream>
using namespace std;
namespace imaging
{
class Image
{
public:
int pixels;
// constructors and destructor
Image(); // default: zero dimensions, nullptr for the buffer.
Image(unsigned int w, unsigned int h);
Image(unsigned int w, unsigned int h, const int data_ptr);
Image(const Image &src);
~Image();
Image & operator = (const Image & right);
};
}
namespace imaging {
Image::Image(){}
Image::Image(unsigned int w, unsigned int h) { std::cout << "built Image!" << std::endl; }
Image::Image(unsigned int w, unsigned int h, const int data_ptr)
{
//memcpy(pixels, data_ptr, sizeof(data_ptr));
}
Image::Image(const Image &src) {}
Image::~Image() {
//if (pixels != nullptr) delete[] pixels;
}
Image& Image::operator=(const Image& right) {
//memcpy(pixels, right.pixels, sizeof(right.pixels));
return *this;
}
}
int main() {
imaging::Image wImage(1,2);
return 0;
}
输出:
built Image!
我也在VS2012中测试了它。
这看起来你在某个地方有一个额外的}。尝试剥离代码,看看是否还有错误。
答案 1 :(得分:0)
然而,我找到了解决方案。我必须在 Image 的标题中包含 ppm_format.h ,但是在.cpp文件中,以避免包含两个标题。