相关疑难解决方法(0)

为什么派生类中的重写函数会隐藏基类的其他重载?

考虑一下代码:

#include <stdio.h>

class Base {
public: 
    virtual void gogo(int a){
        printf(" Base :: gogo (int) \n");
    };

    virtual void gogo(int* a){
        printf(" Base :: gogo (int*) \n");
    };
};

class Derived : public Base{
public:
    virtual void gogo(int* a){
        printf(" Derived :: gogo (int*) \n");
    };
};

int main(){
    Derived obj;
    obj.gogo(7);
}
Run Code Online (Sandbox Code Playgroud)

得到此错误:

>g++ -pedantic -Os test.cpp -o test
test.cpp: In function `int main()':
test.cpp:31: error: no matching function for call to `Derived::gogo(int)'
test.cpp:21: note: candidates are: virtual …

c++ polymorphism overriding

212
推荐指数
3
解决办法
5万
查看次数

为什么我应该使用"using"关键字来访问我的基类方法?

我写下面的代码是为了解释我的问题.如果我注释第11行(使用关键字"using"),编译器不会编译该文件并显示以下错误:invalid conversion from 'char' to 'const char*'.它似乎没有void action(char)Parent类中看到Son类的方法.

为什么编译器会以这种方式运行?或者我做错了什么?

class Parent
{
    public:
        virtual void action( const char how ){ this->action( &how ); }
        virtual void action( const char * how ) = 0;
};

class Son : public Parent
{
    public:
        using Parent::action; // Why should i write this line?
        void action( const char * how ){ printf( "Action: %c\n", *how ); }
};

int main( int argc, char** argv ) …
Run Code Online (Sandbox Code Playgroud)

c++ oop inheritance using

66
推荐指数
4
解决办法
4万
查看次数

c ++问题与继承类中的函数重载

这可能是一个noob问题,抱歉.我最近遇到了一个奇怪的问题,试图在c ++,函数重载和继承中搞乱一些高级的东西.

我将展示一个简单的例子,只是为了证明这个问题;

有两个班,classAclassB如下;

class classA{
    public:
        void func(char[]){};    
};

class classB:public classA{ 
    public:
        void func(int){};
};
Run Code Online (Sandbox Code Playgroud)

据我所知classB,现在应该拥有两个func(..)函数,由于参数不同而重载.

但是在主方法中尝试这个时;

int main(){
    int a;
    char b[20];
    classB objB;
    objB.func(a);    //this one is fine
    objB.func(b);    //here's the problem!
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它给出了错误,因为void func(char[]){}; 超类中的方法classA在派生类中是不可见的classB.

我怎么能克服这个?这不是在c ++中如何重载?我是c ++的新手,但在Java中,我知道我可以使用这样的东西.

虽然我已经找到了这个询问类似问题的帖子,但我认为这两个案例是不同的.

c++ inheritance overloading class

42
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×3

inheritance ×2

class ×1

oop ×1

overloading ×1

overriding ×1

polymorphism ×1

using ×1