死亡钻石和范围解析算子(c ++) [英] Diamond of death and Scope resolution operator (c++)

查看:150
本文介绍了死亡钻石和范围解析算子(c ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码(钻石问题):

  #include< iostream> 
using namespace std;

struct Top
{
void print(){cout<< Top :: print()<< ENDL; }
};

struct右:Top
{
void print(){cout<< Right :: print()<< ENDL; }
};

struct Left:Top
{
void print(){cout<< Left :: print()<< ENDL; }
};

struct Bottom:Right,Left {};

int main()
{
底部b;
b.Right :: Top :: print();
}

我想拨打 print() in Top class。



当我尝试编译它时,我收到错误:'Top'是这一行中'Bottom'的模糊基础: b.Right :: Top :: print();
为什么它含糊不清?我明确指出我希望 Top 来自而不是来自



我不想知道怎么做,是的,它可以用引用,虚拟继承等来完成。我只是想知道为什么是 b.Right :: Top :: print(); 不明确。

解决方案

< blockquote>

为什么它不明确?我明确指出我希望 Top 来自而不是来自


这是你的意图,但事实并非如此。 Right :: Top :: print()明确命名要调用的成员函数,即& Top :: print 。但它没有指定 b 的哪个子对象我们正在调用该成员函数。您的代码在概念上等同于:

  auto print =& Bottom :: Right :: Top :: print; // ok 
(b。* print)(); //错误

选择打印的部分是明确的。这是从 b Top 的隐式转换,这是不明确的。您必须通过以下操作明确消除您进入的方向的歧义:

  static_cast< Right&> (b)中.TOP ::打印(); 


I have this code (diamond problem):

#include <iostream>
using namespace std;

struct Top
{
    void print() { cout << "Top::print()" << endl; }
};

struct Right : Top 
{
    void print() { cout << "Right::print()" << endl; }
};

struct Left : Top 
{
    void print() { cout << "Left::print()" << endl; }
};

struct Bottom: Right, Left{};

int main()
{
    Bottom b;
    b.Right::Top::print();
}

I want to call print() in Top class.

When I try to compile it I get error: 'Top' is an ambiguous base of 'Bottom' on this line: b.Right::Top::print(); Why is it ambiguous? I explicitly specified that I want Top from Right and not from Left.

I don't want to know HOW to do it, yes it can be done with references, virtual inheritance, etc. I just want to know why is b.Right::Top::print(); ambiguous.

解决方案

Why is it ambiguous? I explicitly specified that I want Top from Right and not from Left.

That was your intent, but that's not what actually happens. Right::Top::print() explicitly names the member function that you want to call, which is &Top::print. But it does not specify on which subobject of b we are calling that member function on. Your code is equivalent conceptually to:

auto print = &Bottom::Right::Top::print;  // ok
(b.*print)();                             // error

The part that selects print is unambiguous. It's the implicit conversion from b to Top that's ambiguous. You'd have to explicitly disambiguate which direction you're going in, by doing something like:

static_cast<Right&>(b).Top::print();

这篇关于死亡钻石和范围解析算子(c ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆