这就是我的代码的样子。它有点简化。我正在尝试/想知道我是否可以做的是消除属性类构造函数中对参数的需要。即调用无参数构造函数,并且仍然能够使用 struct value1 项变量填充类项变量,而无需将它们添加为构造函数主体的一部分。
#include <iostream>
using namespace std;
struct value1
{
const int item;
value1( int n ) : item(n) { }
};
struct value2 : public value1
{
value2() : value1(55) { };
};
template <class T>
class property
{
public:
property(T stuff);
void print();
private:
int item;
};
template <class T>
property<T>::property(T stuff) : item(stuff.item) { }
template <class T>
void property<T>::print()
{
cout << item << endl;
}
int main()
{
property<value2> *y = new property<value2>(value2());
y->print();
return 0;
}
最佳答案
call a no arg constructor and still be able to populate the classes item variable with the struct value1 item variable without adding them as part of the constructors body
听起来您只是想要一个工厂方法:
template <class T>
class property {
public:
property();
void print();
static property<T> create(T stuff) {
property<T> p;
p.item = stuff.item;
return p;
}
private:
int item;
};
您可以按如下方式调用它:
auto p = property<value2>::create(value2());
即使我不确定我是否完全符合您的要求。
让我知道,如果我不明白问题,我会删除答案。
关于c++ - 从类的类型结构中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647264/