【发布时间】:2013-03-09 23:14:26
【问题描述】:
我有以下代码
类.h
#ifndef CLASSES_H
#define CLASSES_H
#include <iostream>
using namespace std;
template< class T1, class T2>
class class1
{
public:
virtual void method1(int) const =0;
virtual void method2(class1&) const =0;
};
template< class T1>
class class2:public class1<T1,int>
{
public:
void method1(int) const;
void method2(class2&) const;
};
template< class T1>
void class2<T1>::method1(int i) const
{
cout<<"class2::method1 - before Call %i"<<endl;
cout<<"class2::method1 - after Call"<<endl;
}
template< class T1>
void class2<T1>::method2(class2& c2) const
{
cout<<"class2::method2 - before Call"<<endl;
cout<<"class2::method2 - after Call"<<endl;
}
#endif
main.cpp
#include <cstdlib>
#include <iostream>
using namespace std;
#include "Classes.h"
int main(int argc, char *argv[])
{
class2<int> c2;
c2.method1(0);
c2.method2(c2);
system("PAUSE");
return EXIT_SUCCESS;
}
基本上,C1 是一个接口类,因此它的方法是纯虚拟的。遇到的问题是 Medhod2 传递和类本身的实例(接口是 class1,实现此类接口的类是 class2)。
因此 Method2 有签名
void method2(class1&) const;
在class1和
void method2(class2&) const;
在第 2 类中。
这就是我在编译时收到以下错误的原因。
main.cpp: In function `int main(int, char**)':
main.cpp:12: error: cannot declare variable `c2' to be of type `class2<int>'
main.cpp:12: error: because the following virtual functions are abstract:
Classes.h:14: error: void class1<T1, T2>::method2(class1<T1, T2>&) const [with
T1 = int, T2 = int]
make: *** [main.o] Error 1
我该如何解决这个问题?
有人可以告诉我吗?谢谢。
【问题讨论】:
-
不要写
using namespace std;。它违背了将标准库放在命名空间中的目的。而且,更重要的是,不要将其写在标题中;你会搞砸每一个试图使用你的类的程序员。 -
@Pete Becker 我知道。我只是为了这个例子而使用它。你对我的问题有何建议?
-
我发现很难弄清楚这里要问什么。您似乎想要做的事情无法在 C++ 中完成,但我怀疑如果我们知道您的潜在需求,模板或替代虚拟方法将解决您的实际问题。您能否详细说明您的真正问题,而不是实现的一小部分?
标签: c++ class inheritance interface virtual