通常继承应该让派生类有基类保护和公共(public)变量。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
////ACCOUNT//////
class Account {
protected:
string name;
int balance;
public:
Account(string n) : name{n} {
cout << name << endl;
}
};
////SAVINGS//////
class Savings: public Account {
Savings(string s): name{s} {
cout << "WTFA@A@" << endl;
}
};
int main() {
Account wtf ("wth");
Savings test ("EEE");
return 0;
}
为什么该代码会给我一个错误? Savings 是否应该从 Account 继承名称变量?
此外,如果我想为帐户和储蓄添加存款和取款功能,我是否必须单独添加或继承是否有帮助?两者的取款相同,但存款略有不同,因为储蓄会有利率。
最佳答案
两件事:
首先,如果你想调用父类(super class)的构造函数,那么这样做:
Savings(string s): Account(s) {
...
}
其次,您忘记将子类的构造函数设置为public
。 class
es 中的方法在 C++ 中默认为 private
。
关于c++ - 继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54873572/