繁体   English   中英

C ++中另一个类中的模板类实例化

[英]template class instantiation in another class in c++

我有一个模板类,当我在main中实例化时没有任何问题,但是当我尝试在另一个类中实例化时却给出了问题。 有人可以给我启发一下解决方案吗

#include<iostream>
#include<string>
using namespace std;

template <class T>
class property {
public:
    property(string name)
    {
        propertyName= name;
    }
private:
    T item;
    string propertyName;
};
main()
{
    property<int> myIntProperty("myIntProperty");
}

上面的代码编译没有任何问题。

#include<iostream>
#include<string>
using namespace std;

template <class T>
class property {
public:
    property(string name)
    {
        propertyName= name;
    }
private:
    T item;
    string propertyName;
};

class propertyHolder
{
    property<int> myIntProperty("myIntProperty");
};

此代码未得到编译。 给我像这样的错误

main.cpp | 19 |错误:字符串常量前的预期标识符| main.cpp | 19 |错误:字符串常量前应有','或'...'

谢谢,哈里斯

property<int> myIntProperty("myIntProperty");

这是一个函数声明,因此希望您在识别后插入默认参数,例如string s = "myIntProperty"

也许您想初始化一个名为myIntProperty的对象,

property<int> myIntProperty {"myIntProperty"};

这可以在C ++ 11中完成,但是您也可以在构造函数初始化器列表中对其进行初始化,

// Header
class propertyHolder {
public:
    propertyHolder( string s );
private:
    property<int> myIntProperty;
};

// Source
propertyHolder::propertyHolder( string s ) :
    myIntProperty( s )
{
}

您想在class propertyHandler声明字段。 该语法不起作用,因为您无法在同一位置声明字段并将其值赋值。

您可以删除它,并在构造函数中初始化:

property<int> myIntProperty;

propertyHolder(): myIntProperty("name") {}

或使用c ++ 11语法:

property<int> myIntProperty{"name"};

或将其声明为静态,然后他们这样声明:

static property<int> myIntProperty;

在类声明之后:

property<int> propertyHolder::myIntProperty("name");

暂无
暂无

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

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