类型转换二义性
class A { };
class B { };
class C : public A, public B { };
void print(A & a) {}
void print(B & a) {}
int main() {
C c;
print(c); // 二义性
return system("pause");
}
基类的构造顺序与派生列表中基类的顺序一致
代码
class A {
public:
A() { std::cout << "A()" << std::endl; }
};
class B {
public:
B() { std::cout << "B()" << std::endl; }
};
class C : public A, public B {
public:
C() = default;
};
class D : public B, public A {
public:
D() = default;
};
int main() {
C c;
std::cout << "--------------" << std::endl;
D d;
return system("pause");
}
输出结果
A()
B()
--------------
B()
A()
继承基类构造函数
class A {
public:
A() { std::cout << "A()" << std::endl; }
A(int a) { std::cout << "A(int a)" << std::endl; }
A(char a) { std::cout << "A(char a)" << std::endl; }
};
class B {
public:
B() { std::cout << "B()" << std::endl; }
B(double a) { std::cout << "B(double a)" << std::endl; }
B(char a) { std::cout << "B(char a)" << std::endl; }
};
class C : public A, public B {
public:
using A::A;
using B::B;
C() { std::cout << "C()" << std::endl; }
C(char a) { std::cout << "C(char a)" << std::endl; }
};
// 多重继承中继承构造函数时,派生类的其他成员执行默认初始化
int main() {
std::cout << "--------------" << std::endl;
C a(0);
std::cout << "--------------" << std::endl;
C b(0.0);
std::cout << "--------------" << std::endl;
C c('0');
std::cout << "--------------" << std::endl;
return system("pause");
}
名字查找二义性问题
注意:编译器并不检查可取用性,即便实际上只有一个可取用
class A {
public:
void doSomething1() {}
void doSomething2() {}
void doSomething3() {}
int a;
};
class B {
public:
void doSomething1() {}
void doSomething2(int) {}
private:
void doSomething3() {}
int a;
};
class C : public A, public B {
};
int main() {
C c;
c.doSomething1(); // 错误
c.doSomething2(); // 错误
c.doSomething3(); // 错误
c.a;
return system("pause");
}