2

我有一个接口,我正在尝试一个关于动态多态的示例,如下所示:

#include <iostream>

using namespace std;

class foo{
    public:     
        virtual void set();
        virtual void printValue();
};

class fooInt : public foo{
        private:
            int i;
        public:
            int get(){ 
                return i;
            }   
            void set(int val){ //override the set
                i = val;
            }
            void printValue(){
                cout << i << endl;
            }           
};

int main(){
    foo *dt;         //Create a base class pointer
    dt = new fooInt; //Assign a sub class reference
    dt->set(9);
}

但是,当我编译它时,我没有得到调用 'foo::set(int)' 的匹配函数。我哪里错了?我试图阅读这篇文章,但我仍然无法找出错误。

4

3 回答 3

1

class foo has no method set(int). It has a method set(), but no method set(int).

If you intend to override an inherited method, the superclass method and your method must have the same signature:

class foo {
  ...
  // If you really want an abstract class, the `= 0`
  //  ensures no instances can be created (makes it "pure virtual")
  virtual void set(int) = 0;
  ...
}
于 2013-04-29T01:08:52.540 回答
1

这是因为你的定义

    virtual void set(); 

应该

    virtual void set(int val); 
于 2013-04-29T01:10:41.423 回答
1

更正的程序在这里给出

#include <iostream>

using namespace std;

class foo {

public:
    virtual  void set(int val)=0;////////here you have void set() function with no argument but you tried to override void set(int val) which take one argument.
    virtual void printValue()=0;
};

class fooInt : public foo{
private:
    int i;
public:

    fooInt()
    {
        cout<<"constructor called\n";
    }
    int get(){
        return i;
    }
    void set(int val){ //override the set


        i = val;
    }
    void printValue(){
        cout << i << endl;
    }
};

int main(){


    foo *dt;       //Create a base class pointer
    dt=new fooInt;
    dt->set(9);
    dt->printValue();
}

上一个程序的故障是

1.你试图用 set(int val){one argument} 覆盖 set() {no argument}。2.当一个类包含一个纯虚函数时,它必须由它的派生类来实现。3. 不能为包含纯虚函数的类创建对象,但可以创建 ref。谢谢

于 2013-05-02T14:25:15.080 回答