To have like 3 functions with same names like:
bool VideoEncoder::AddFrame(AVFrame* frame, const char* soundBuffer, int soundBufferSize)
bool VideoEncoder::Add开发者_Python百科Frame( const char* soundBuffer, int soundBufferSize)
bool VideoEncoder::AddFrame(AVFrame* frame)
Can we?
Yes, it's called function overloading, and is a standard feature of C++.
The functions must be resolvable based on the quantity and types of the parameters you pass to them. This will break if, e.g., you define the following overloads:
void A::foo(long n);
void A::foo(double n);
A a;
int i = 42;
a.foo(i);
This will produce an unresolvable ambiguity.
Absolutely. Functions in C++ are differentiated by their names and arguments (but not their return value). So to the compiler, these are just different functions (or methods).
But when the arguments are different, it is called 'overloading', not 'overriding'. The latter is when you have a function with the same name and arguments in a subclass.
Not only is it possible, but it is a very useful feature of C++ called function overloading.
Also note that functions who share the same name must differ by more than their only return type, but they may differ in their const-ness only (and this is incredibly frequent and useful) :
struct A
{
void doSomething() { std::cout << "A" << std::endl; }
void doSomething() const { std::cout << "B" << std::endl; }
// int doSomething(); /* illegal : differs only by return type */
double doSomething(int); /* OK : differs by return type and parameters */
};
int main()
{
A a;
const A constA;
a.doSomething(); // prints "A"
constA.doSomething(); // prints "B"
}
Yes, this is correct. Overloaded functions must have the same name, return type and different set of parameters.
精彩评论