C++ 继承重载具有不同参数的函数
C++ inheritance overloads functions with different parameters
我正在开发一个项目,该项目使用 class 继承并且需要在基础和派生中进行大量重载 class,我已经简化了代码,但我不想不必要地复制和粘贴,因为这应该是继承的目的。
#include <iostream>
class Base
{
public:
Base() = default;
//base const char* overload
void foo(const char* message)
{
std::cout << message << std::endl;
}
//other overloads ...
};
class Derived : public Base
{
public:
Derived() = default;
//derived int overload
void foo(int number)
{
std::cout << number << std::endl;
}
};
int main()
{
Derived b;
b.foo(10); //derived overload works
b.foo("hi"); //causes error, acts as if not being inherited from Base class
return 0;
}
您可以在派生的 class 中使用 using 声明,例如
using Base::foo;
使在派生 class 中可见在基 class 中声明的重载函数 foo。
这是您的程序,其中插入了 using 声明。
#include <iostream>
class Base
{
public:
Base() = default;
//base const char* overload
void foo(const char* message)
{
std::cout << message << std::endl;
}
//other overloads ...
};
class Derived : public Base
{
public:
Derived() = default;
using Base::foo;
//derived int overload
void foo(int number)
{
std::cout << number << std::endl;
}
};
int main()
{
Derived b;
b.foo(10); //derived overload works
b.foo("hi"); //causes error, acts as if not being inherited from Base class
return 0;
}
程序输出为
10
hi
我正在开发一个项目,该项目使用 class 继承并且需要在基础和派生中进行大量重载 class,我已经简化了代码,但我不想不必要地复制和粘贴,因为这应该是继承的目的。
#include <iostream>
class Base
{
public:
Base() = default;
//base const char* overload
void foo(const char* message)
{
std::cout << message << std::endl;
}
//other overloads ...
};
class Derived : public Base
{
public:
Derived() = default;
//derived int overload
void foo(int number)
{
std::cout << number << std::endl;
}
};
int main()
{
Derived b;
b.foo(10); //derived overload works
b.foo("hi"); //causes error, acts as if not being inherited from Base class
return 0;
}
您可以在派生的 class 中使用 using 声明,例如
using Base::foo;
使在派生 class 中可见在基 class 中声明的重载函数 foo。
这是您的程序,其中插入了 using 声明。
#include <iostream>
class Base
{
public:
Base() = default;
//base const char* overload
void foo(const char* message)
{
std::cout << message << std::endl;
}
//other overloads ...
};
class Derived : public Base
{
public:
Derived() = default;
using Base::foo;
//derived int overload
void foo(int number)
{
std::cout << number << std::endl;
}
};
int main()
{
Derived b;
b.foo(10); //derived overload works
b.foo("hi"); //causes error, acts as if not being inherited from Base class
return 0;
}
程序输出为
10
hi