kod*_*off 1 c++ virtual-inheritance
我目前正在开发一个C++项目,我有一个稍后实现的抽象接口.该接口还有一个实现的方法,我的实现不会覆盖.我的问题是,在使用我的实现时,编译器(MSVC)没有看到接口方法.是什么导致这种情况,我该如何解决?
这是代码.
#include <string>
#include <vector>
using std::string;
class A
{
public:
string name;
};
class interface
{
public:
virtual int num_foo() = 0;
virtual A* foo(int) = 0;
virtual A* foo(string &name){
for ( int i(0); i < num_foo(); i++)
if ( foo(i)->name == name )
return foo(i);
return 0;
}
};
class implementation : public interface
{
public:
virtual int num_foo() { return m_foos.size(); }
virtual A* foo(int i) {
//check range
return &m_foos[i];
}
std::vector<A> m_foos;
};
int main(...)
{
implementation impl;
// impl is properly initialized here
string name( "bar" );
// here comes my problem, the MSVC compiler doesn't see foo(string &name)
// and gives an error
A *a = impl.foo( name );
}
Run Code Online (Sandbox Code Playgroud)
名称解析在重载解析之前发生.在impl.foo( name ),然后编译器查看implementation该类并仅查找virtual A& foo(int i).它没有查看基类,因为它找到了一个具有正确名称的函数.
要更正此用法,可以using interface::foo向派生类添加一个声明,以便将所有基本版本拉foo入派生类,以便进行重载解析.通常,我宁愿避免重载函数,我可能会给出foo不同函数名的变体.
(其他错误是您没有定义的string,vector或者m_ones;您尝试使用->而不是.在引用上,并且尝试在返回引用的函数中返回0.A)
| 归档时间: |
|
| 查看次数: |
133 次 |
| 最近记录: |