如何初始化继承的值,并拥有抽象方法 C++?

huangapple go评论77阅读模式
英文:

How to initialize inherited values, and have abstract methods c++?

问题

这有点像一个问题中的多个问题。首先,C++ 中有没有一种方法可以初始化继承的值?换句话说,这就是我在 Java 中的意思:

// Class X
class X {
public:
    int num;
    X(int num) : num(num) {}
};

// Class Y
class Y : public X {
public:
    Y() : X(5) {}
};

我的另一个问题是,我如何在 C++ 中创建一个抽象方法?同样,Java 示例:

// Class X
class X {
public:
    int num;
    X(int num) : num(num) {}
    virtual void use() = 0;
};

// Class Y
class Y : public X {
public:
    Y() : X(5) {}

    void use() override {

    }
};

谢谢。

英文:

This is kinda multiple questions in a single question. First off, is there a way to initialize inherited values in C++? In other words, this is what I mean in java :

// Class X
public class X {
    int num;
    public X(int num) {
        this.num = num;
    }
}

//Class Y
public class Y extends X{

    public Y() {
        super(5);
    }
}

My other question is how would I create an abstract method in C++?
Again, java example :

// Class x
public abstract class X {
    int num;
    public X(int num) {
        this.num = num;
    }
    public abstract void use();
}
// Class y
public class Y extends X{

    public Y() {
        super(5);
    }

    @Override
    public void use() {

    }
}

Thanks.

答案1

得分: 2

首先:您想了解初始化列表。对于您的第一个代码片段,适当的代码应为

class X {
    int num;
public:
    X(int t_num) : num(t_num) { } // 我们可以使用初始化列表来设置成员变量
};

class Y : public X {
public:
    Y() : X(5) { } // 在构造函数的主体中不需要有任何内容
};

对于第二个问题,在C++中,您可以在不提供定义的情况下声明函数,这与Java中定义抽象函数非常相似。如果您的目的是进行运行时多态性,您还需要将它们声明为虚函数

class X {
    int num;
public:
    virtual void use() = 0; // = 0 表示在X中没有实现
};

class Y : public X {
    void use() override { } // 不需要重新声明虚函数
                            // override 关键字不是必需的,但可以澄清语义
};
英文:

First: You want to learn about initializer lists. For your first code snippet, the appropriate code would be

class X {
    int num;
public:
    X(int t_num) : num(t_num) { } // We can use initializer lists to set member variables
};

class Y : public X {
public:
    Y() : X(5) { } // No need to have anything in the body of the constructor
};

For the second, in C++ you can always declare functions without providing a definition, which is very similar to defining an abstract function in Java. If your intent is to do run-time polymorphism, you'll also want to make them virtual functions:

class X {
    int num;
public:
    virtual void use() = 0; // The = 0 indicates there's no implementation in X
};

class Y : public X {
    void use() override { } // No need to redeclare virtual
                            // override keyword not necessary but can be clarifying
};

huangapple
  • 本文由 发表于 2020年10月7日 07:34:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64235178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定