C++中的二义性问题

直接贴代码吧。。。没啥好说的。。。

 

#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Base1
{
    void print(int) const{
        cout<<"Base1"<<endl;
    }
protected:
    int ival;
    double dval;
    char cval;
private:
    int *id;
};
struct Base2
{
    void print(double )const{
        cout<<"Base2"<<endl;
    }
protected:
    double fval;
private:
    double dval;
};
struct Derived:public Base1
{
    void print(std::string) const{
        cout<<"Derived"<<endl;
    }
protected:
    std::string sval;
    double dval;
};
struct MI:public Derived,public Base2
{
    void print(std::vector<double>)
    {
        cout<<"MI"<<endl;
    }
    void f()
    {
        dval=3.1;//导致二义性,就是因为分不清到底是Derived里头的dval还是Base1的dval
    }
protected:
    int *ival;
    std::vector<double>dvec;
};

int main(int argc, char *argv[])
{
    MI mi;
    mi.print(42);//同样是二义性,得写成mi.Base1::print(42)
    return 0;
}

 

posted @ 2018-05-11 10:28  ExitQuit  阅读(351)  评论(0编辑  收藏  举报