简体   繁体   English

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

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

This is kinda multiple questions in a single question.这是一个问题中的多个问题。 First off, is there a way to initialize inherited values in C++?首先,有没有办法在 C++ 中初始化继承的值? In other words, this is what I mean in java :换句话说,这就是我在 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++?我的另一个问题是如何在 C++ 中创建抽象方法? Again, java example :再次,java 示例:

// 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.谢谢。

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.其次,在 C++ 中,你总是可以在不提供定义的情况下声明函数,这与在 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
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM