If a class inherits from two classes defines a certain function would happen then

如果一个类同时继承的两个类都定义了某一个函数会怎样呢 | Code4Fun box

As shown in the following: class Cinherits both Aand B, and both define the same function, if this time, then the compiler will get an error.

         
         
1
2
3
4
5
6
7
8
9
10
         
         
testhir.cpp: In function ‘int main(int, const char**)’:
testhir.cpp:26:7: error: request for member ‘printR’ is ambiguous
c.printR ();
^~~~~~
testhir.cpp:5:14: note: candidates are: void A::printR()
Among void ()
^~~~~~
testhir.cpp: 13: 14: Notes: B :: through the void ()
Among void ()
^~~~~~
         
         
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
         
         
#include <iostream>
class A {
public:
void printR()
{
std::cout << "in A" << std::endl;
}
};
class B {
public:
void printR()
std::cout << "in B" << std::endl;
}
};
class C :B,A {
public:
};
int main(int argc, const char** argv) {
C c;
c.printR();
return 0;
}

如果在C中也实现了相同的函数的话,就可以正常编译获得结果:in C

         
         
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
         
         
#include <iostream>
class A {
public:
void printR()
{
std::cout << "in A" << std::endl;
}
};
class B {
public:
void printR()
{
std::cout << "in B" << std::endl;
}
};
class C :B,A {
public:
void printR()
{
std::cout << "in C" << std::endl;
}
};
int main(int argc, const char** argv) {
C c;
c.printR();
return 0;
}

呼呼呼山(http://code4fun.me)
2019-05-24 15:40:15

Guess you like

Origin www.cnblogs.com/lijianming180/p/12046836.html