生成未解析的外部符号的调用:
#include <string.h>
#include "GContext.h"
#include "GBitmap.h"
#include "GColor.h"
int main(int argc, char** argv) {
const int W = 100;
const int H = 100;
GContext* ctx = GContext::Create(W, H);
抽象类方法签名:
#ifndef GContext_DEFINED
#define GContext_DEFINED
#include "GTypes.h"
class GBitmap;
class GColor;
class GContext {
public:
GContext() {}
virtual ~GContext() {}
virtual void getBitmap(GBitmap*) const = 0;
virtual void clear(const GColor&) = 0;
static GContext* Create(const GBitmap&);
static GContext* Create(int width, int height);
};
#endif
当前派生类实现和方法签名:
#include "GColor.h"
#include "GPixel.h"
#include "GBitmap.h"
#include "GContext.h"
#include "GTypes.h"
class myGContext : public GContext
{
public:
myGContext() : GContext(){}
static const GBitmap* bitmap;
void getBitmap(GBitmap* bitmap) const
{
}
void clear(const GColor& gcolor)
{
int length = sizeof( (GPixel)(bitmap->fPixels) ) / sizeof(GPixel);
for (int i = 0; i < length; i++)
{
(bitmap->fPixels)[i]
}
}
static GContext* Create(const GBitmap& gbitmap)
{
GContext::Create(gbitmap);
bitmap = &gbitmap;
GContext* g = new myGContext();
return g;
}
static GContext* Create(int width, int height)
{
GContext::Create(width,height);
GContext* g = new myGContext();
return g;
}
};
所以我理解我需要定义函数GContext :: Create()的两种类型来解决外部符号错误,但我需要在派生类中定义它们。我认为我做得对,任何想法?
答案 0 :(得分:0)
否继承不起作用,这不像虚函数。
答案 1 :(得分:0)
我不确定你要做什么但是如果你
这一切都是可以实现的:
#include <iostream>
class A {
public:
A() {}
static void f() { std::cout << "A f" << std::endl; }
};
class B : public A {
public:
B() {}
static void f() { std::cout << "B f" << std::endl; }
};
int main(int argc, char* argv[]) {
A a;
B b;
a.f();
b.f();
b.A::f();
return 0;
}
输出
A f
B f
A f
答案 2 :(得分:0)
我认为这只是因为你的基类中没有定义静态方法。从here开始,当声明静态数据成员但未定义静态数据成员时,也会发生 LNK2019。
另外,当您尝试在子类中重新定义静态方法时要小心:
您无法覆盖子类中的静态方法,您只能隐藏它。
从C ++标准:
9.4.1静态成员函数[class.static.mfct]
2 /
static
成员函数不应为virtual
。不应有static
和具有相同名称和相同参数类型的非静态成员函数(13.1)。static
成员函数不得声明为const
,volatile
或const volatile
。
#include <iostream>
class Foo
{
public:
static void func() { std::cout << "Foo::func" << std::endl; }
};
class Bar : public Foo
{
public:
static void func() { std::cout << "Bar::func" << std::endl; }
};
int main(void)
{
Foo::func(); // Works
Bar::func(); // Works
Foo foo;
Bar bar;
foo.func(); // Works
bar.func(); // Works
bar.Foo::func(); // Works
Foo* foobar = new Bar;
foobar->func(); // Not the result expected
// Because no override.
return 0;
}