0

okay, i'm curious why gcc calls this an ambiguity. check this:

class base_stream
{
public:
    std::string m_buffer;
};

class idatastream : public base_stream
{

};

class odatastream : public base_stream
{

};

class datastream : public idatastream, public odatastream
{
public:
    void dostuff( m_buffer = "some text";) // reference is ambiguous?
};

i declare m_buffer only once in base_stream, and do not redeclare it in the inheriting classes, so why is it that when i inherit from both the inheriting classes, m_buffer is ambiguous? the error says this:

||In member function 'void datastream::dostuff()':|
|22|error: reference to 'm_buffer' is ambiguous|
|6|error: candidates are: std::string base_stream::m_buffer|
|6|error: std::string base_stream::m_buffer|
||=== Build finished: 3 errors, 0 warnings ===|

i'm confused here because the valid candidates are the same. when i change the defintion of dostuff to:

void dostuff() {base_stream::m_buffer = "test string";}

, like it suggests, i get this error:

||In member function 'void datastream::dostuff()':|
|22|error: 'base_stream' is an ambiguous base of 'datastream'|
||=== Build finished: 1 errors, 0 warnings ===|

This is where i think the heart of the problem lies. Am i not able to inherit from two classes that inherit from the same class?

4

1 回答 1

1

您需要继承idatastreamodatastreambase_stream使用虚拟继承。

所以这样的事情可能会奏效。

class base_stream
{
public:
    std::string m_buffer;
};

class idatastream : virtual public base_stream
{

};

class odatastream : virtual public base_stream
{

};

class datastream : public idatastream, public odatastream
{
public:
    void dostuff( m_buffer = "some text";) // reference is ambiguous?
};

base_stream因此,在这种情况下,内部仅存在一个副本,可以data_stream访问m_buffer.data_stream

我希望我回答了你的问题。

于 2012-04-10T22:22:21.827 回答