【发布时间】:2013-10-15 21:01:10
【问题描述】:
我对 C++ 很陌生。今天,我在混合嵌套类和接口时遇到了一些问题。
我写了一个小(无用)程序,它比长句更能有效地解释我的问题:
#include <iostream>
#include <vector>
class SomeInterface {
public:
virtual int SomeMethod() = 0;
class reference {
public:
virtual operator int() const = 0;
virtual reference& operator=(int x) = 0;
};
virtual reference operator[](unsigned int pos) = 0;
};
class A : public SomeInterface {
public:
A(unsigned int size) { vec_.resize(size, 0); }
int SomeMethod() { return 1; }
class reference : public SomeInterface::reference {
public:
reference(std::vector<int>::reference ref) : ref_(ref) { }
operator int() const { return (int) this->ref_; }
reference& operator=(int x) { this->ref_ = x; return *this; }
private:
std::vector<int>::reference ref_;
};
reference operator[](unsigned int pos) {
return reference(this->vec_[pos]);
};
private:
std::vector<int> vec_;
};
int main() {
A a(10);
a[5] = 42;
std::cerr << a[5] << std::endl;
return 0;
}
在这里,如果我删除界面中的virtual reference operator[](unsigned int pos) = 0; 行,程序编译正常。但是,我希望数组下标运算符成为接口的一部分。
G++抛出的错误信息是invalid abstract return type for member function ‘virtual SomeInterface::reference SomeInterface::operator[](unsigned int)’。
我明白它为什么会失败。但我想不出任何办法来做这样的事情。谁能解释我为什么做错(或思考)错了?
【问题讨论】:
-
如果你想重写一个虚函数,返回类型必须是协变的。您可以在此处通过返回对
reference的引用或指针来执行此操作,但这可能会破坏reference类的要点。
标签: c++ interface nested-class