madf: (Default)
[personal profile] madf
Дещо незвичне використання using.
Маємо базовий клас з парою overloaded методів:

class Base {
public:
void foo() const { std::cout << "Base::foo()" << std::endl; }
void foo(int v) const { std::cout << "Base::foo(int v = " << v << ")" << std::endl; }
};
_Winnie C++ Colorizer

Від нього наслідується нащадок з таким-же методом:

class Derived : public Base {
public:
void foo(const std::string & v) const { std::cout << "Derived::foo(const std::string & v = \"" << v << "\")" << std::endl; }
};
_Winnie C++ Colorizer

В результаті при використанні нащадку методи базового класу не доступні:

int main()
{
Derived d;

d.foo();
d.foo(1);
d.foo("abc");

return 0;
}
_Winnie C++ Colorizer

$ g++ test.cpp -o test                                                          
test.cpp: In function ‘int main()’:                                             
test.cpp:19:11: error: no matching function for call to ‘Derived::foo()’        
test.cpp:11:14: note: candidate is: void Derived::foo(const std::string&) const 
test.cpp:20:12: error: invalid conversion from ‘int’ to ‘const char*’           
test.cpp:20:12: error:   initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’

Для того щоб мати можливість використовувати ці методи треба явно вивести їх у нащадка через using:

class Derived : public Base {
public:
void foo(const std::string & v) const { std::cout << "Derived::foo(const std::string & v = \"" << v << "\")" << std::endl; }
using Base::foo;
};
_Winnie C++ Colorizer

$ g++ -W -Wall -Wextra test.cpp -o test
$ ./test 
Base::foo()
Base::foo(int v = 1)
Derived::foo(const std::string & v = "abc")

Альтернатива - явне вказування базового класу під час виклику:

int main()
{
Derived d;

d.Base::foo();
d.Base::foo(1);
d.foo("abc");

return 0;
}
_Winnie C++ Colorizer


Інфа від самого Герба Саттера ("Please explain: function overloading with virtual functions. ")!

Profile

madf: (Default)
madf

April 2018

S M T W T F S
1234567
891011121314
15161718192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 7th, 2026 05:46 am
Powered by Dreamwidth Studios