-2

我有一个简单的类和一个静态成员函数:

class Matrix
{
public: 
    static Matrix returnSomething ( Matrix &m )
    {
        return Matrix(2,2);
    }
};

主功能:

int main()
{
    Matrix matrix(2,2);                           // some matrix
    Matrix m = Matrix::returnSomething ( matrix ) // I should use it that way
    m.print() // it shows the matrix       

    // but I can use it too that way //

    Matrix m;
    m.returnSomething ( matrix )                  // how to make this not allowed??
    m.print() // but here the matrix is NULL, wont show anything 
}

怎么做?

编辑:

我添加了一些显示问题的打印功能

4

3 回答 3

3

它不应该有所作为。但是,您可以使用命名空间而不是静态函数

namespace MatrixUtils
{
  Matrix returnSomething ( Matrix &m )
  {
     return Matrix(2,2);
  }
}
于 2013-05-02T12:24:11.387 回答
3

你混淆了两个问题。返回值“消失”是因为您没有将它分配给任何东西 - 这与您调用函数的方式无关。

换句话说,这些都可以工作:

Matrix matrix(2, 2);
Matrix m = Matrix::returnSomething(matrix);
Matrix m2 = m.returnSomething(martix);

虽然这些都会使返回值“消失:”

Matrix matrix(2, 2);
Matrix::returnSomething(matrix);
matrix.returnSomething(martix);
于 2013-05-02T12:42:55.293 回答
1

为什么不直接使用辅助类?

class MatrixHelper
{
public: 
    static Matrix returnSomething ( Matrix &m )
    {
        return Matrix(2,2);
    }
};

那么调用将是:

MatrixHelper::returnSomething ( matrix ) 
于 2013-05-02T12:25:17.450 回答