2013-01-11 92 views
1

我有一个类Sparse_Matrix,它允许我有效地使用稀疏矩阵。C++ MatLab构造函数重载

我想通过使用特定的(习惯)的关键字,例如上,身份等来实例化一个特定的矩阵

这是我的类声明(命名空间矩阵)

template <typename T> 
class Sparse_Matrix 
{ 

    private: 
    int rows; 
    int cols; 
    std::vector<int> col; 
    std::vector<int> row; 
    std::vector<T> value; 
    ... 

是否有获得预初始化对象的方法?

Sparse_Matrix<int> = Eye(3); 

将返回一个3乘3的单位矩阵。

我已经看过构造函数的成语,但那些需要一些与我的类不兼容的静态类型的软(尽管我愿意接受建议)。

我自己也尝试这样的代码:

template <typename T> 
Sparse_Matrix<T> Eye(int size) 
{ 
    Sparse_Matrix<T> ma; 
    ma.IdentityMatrix(size); 
    std::cout << "Eye!" << std::endl; 
    return ma; 
} 

...

Sparse_Matrix<int> blah = Eye(10); 

,但无济于事。

谢谢

SunnyBoyNY

+1

什么 “但无济于事。”具体是指? – JaredC

+0

编译器错误是:'没有匹配的函数调用“Eye(int)”' – SunnyBoyNY

回答

2

在C++中只有一个地方可以根据表达式的使用方式推导出模板参数:用户定义的转换运算符。

struct Eye 
{ 
    int size; 
    explicit Eye(int requestedSize) : size(requestedSize) {} 

    template<typename T> 
    operator SparseMatrix<T>() const { SparseMatrix<T> ma; ma.IdentityMatrix(size); return ma; } 
}; 

现在你可以写

Sparse_Matrix<int> blah = Eye(10); 
+0

看来我的GCC编译器遇到一个错误:'错误:ISO C++禁止声明'Eye'没有类型'。和'错误:只有构造函数的声明可以是显式的'。 – SunnyBoyNY

+0

@SunnyBoyNY:那你拼错了什么。它编译的很好 - http://ideone.com/C1CcUG(使用vector而不是'SparseMatrix',我没有定义) –

+0

当然我犯了一个拼写错误 - 我将结构重命名为Eye2,但是在'explicit'语句之后不重命名眼睛。 – SunnyBoyNY

2

有了这样的构造你的对象是一个很好的策略功能。在你的榜样,一个解决方案是专门来告诉Eye类型:

Sparse_Matrix<int> blah = Eye<int>(10); 

有时,这些功能是在类中的静态为了清晰:

template<typename T> 
class Sparse_Matrix 
{ 
public: 
    static Sparse_Matrix<T> Eye(...) {...} 
}; 

在这种情况下,你会打电话:

Sparse_Matrix<int> blah = Sparse_Matrix<int>::Eye(10); 
+0

那么,你实际上并不需要,你只需要添加一个可引用的上下文。 –

+0

@Ben我看到你的答案,有趣的... – JaredC

+0

@JaredC它看起来像我刚刚缺少构造函数<>。现在,为什么这些函数被声明为静态的? – SunnyBoyNY