有什么机制可以将属性从派生类传递到基类,以便:
属性是一个与派生类的每个对象相关的常数。
最佳答案
如果您的问题是“将属性从派生类传递到基类的机制是什么?”有两种方法可以做到这一点。
#include <iostream>
class Base
{
public:
Base(const char *a)
{
std::cout << a << std::endl;
}
};
class Derived : public Base
{
public:
Derived(const char *a)
: Base{a} { }
};
int main()
{
Derived d{"Parent initialization through member initializer list"};
// console output: Parent initialization through member initializer list
}
#include <iostream>
class Base
{
public:
Base(const char *a)
{
std::cout << a << std::endl;
}
};
class Derived : public Base
{
public:
using Base::Base;
};
int main()
{
Derived d{"Parent class initialization through constructor inheritance"};
// console output: Parent class initialization through constructor inheritance
}
用模板类看一个有用的例子#include <iostream>
#include <vector>
template<class T>
class custom_vector : public std::vector<T>
{
public:
// I will inherit all std::vector constructors
using std::vector<T>::vector;
// ...
};
int main()
{
// Inizializer list constructor
custom_vector<int> v{1, 2, 3, 4, 5};
for (auto x : v) std::cout << x << std::endl;
// 1 2 3 4 5
// Fixed-allocation with default value constructor
custom_vector<char> v2(10, 'A');
for (auto x : v2) std::cout << x << std::endl;
// A A A A A A A A A A
}
如果没有使用std::vector 在您的示例中,我注意到一些设计缺陷
关于c++ - 将属性传递给基类的机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63490306/