【问题标题】:C++: class that stores object with unknown type as member variableC ++:将具有未知类型的对象存储为成员变量的类
【发布时间】:2019-10-19 11:25:36
【问题描述】:

我是 C++ 初学者,正在尝试定义使用未知类型对象的类。此类应将此对象作为参数,然后将其存储为成员变量。

我知道我需要使用模板来解决这类问题。我还设法完成了有效的模板功能,但我在课堂上遇到了问题。希望代码示例能澄清我的问题。

只需定义几个用于测试目的的基类:

#include <iostream>
using namespace std;

class Base
{
public:
    string m_s;

    Base(string s)
    {
        m_s = s;
    }

    void print()
    {
        cout << "Hello " + m_s << endl;
    }
};

class Base2
{
public:
    string m_s;

    Base2(string s)
    {
        m_s = s;
    }

    void print()
    {
        cout << "Hey " + m_s << endl;
    }
};

定义应将对象作为参数并将其存储为成员变量的派生类:

template <typename T>
class Derived
{
public:
    T m_c;

    Derived(T c)
    {
        T m_c = c;
    }

    void print()
    {
        m_c.print();
    }
};

测试:

int main(int argc, char const *argv[])
{
    auto b1 = Base("b1");
    auto b2 = Base2("b2");

    // This will give compile error:
    // no matching function for call to ‘Base::Base()’ 
    auto d1 = Derived<Base>(b1);
    auto d2 = Derived<Base2>(b2);
    d1.print();
    d2.print();
}

另一方面,如果我只是定义函数模板,它可以正常工作。

template <typename T>
void print(T c)
{
    c.print();
}

int main(int argc, char const *argv[])
{
    auto b1 = Base("b1");
    auto b2 = Base2("b2");

    // This works!
    print(b1);
    print(b2);

} 

任何帮助将不胜感激。

【问题讨论】:

标签: c++ templates


【解决方案1】:

您的类没有默认构造函数,在这种情况下,请尝试以下代码:

 Derived(T c) : m_c(c)
{

}

或者您可以将 Base2() {} 和 Base() {} 添加到相应的类中。 但在这种情况下,这些类的所有成员都将调用默认构造函数,并且您将打印默认值。

Also I`d like to advise you to read the rule of three. 这将使您更好地理解问题。

【讨论】:

  • 感谢您的回答和链接!
猜你喜欢
  • 2019-01-06
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多