C++ 构造函数使用什么

C++ 构造函数使用什么,c++,C++,我必须设计一个继承自vector的类int2d,以便以下代码: int main() { int2d t1(4, 3); for(int i = 0; i < 4; i++) { for(int j = 0; j < 3; j++) { t1(i, j) = i + j; } } for(int i = 0; i < 4; i++) {

我必须设计一个继承自
vector
的类int2d,以便以下代码:

int main() 
{ 
    int2d t1(4, 3);

    for(int i = 0; i < 4; i++) 
    {
        for(int j = 0; j < 3; j++)
        { 
            t1(i, j) = i + j;
        }
    }

    for(int i = 0; i < 4; i++) 
    { 
        for(int j = 0; j < 3; j++)
            cout << t1(i, j) << " "; 
        {
            cout<<endl; 
        }
    } 
}
我已经写过:

class int2d : public vector<vector<int>> {
public:
    vector<vector<int>> vec;
    int a;
    int b;

    //vector<int> tmp;
    //vector<vector<int>> vec(b);
    int2d(int a, int b) {

        vector<int> tmp(b);
        vector<vector<int>> vec(a);
        for(int i = 0; i < a; i++) {
            vec.push_back(tmp);
        }
    }

    int2d& operator = (const int2d& X){
        if (this == &X)
            return *this;
        int2d tmp(X.a, X.b);
    }

    int2d& operator = (const int& X){
        vec[a][b] = X;
    }
};
class int2d:公共向量{
公众:
向量向量机;
INTA;
int b;
//向量tmp;
//载体vec(b);
int2d(inta,intb){
载体tmp(b);
向量vec(a);
for(int i=0;i

但是我怎样才能使
t1(I,j)=I+j编译并工作?

您只需要
操作符()(std::size\u t,std::size\u t)
可能同时包含
const
和非
const
重载


但我强烈建议不要从标准容器继承。只需将标准容器作为类中的成员。

你必须知道为什么int2d继承自vector?我的代码无效,我无法编译它。可能没有理由继承自vector。好吧,它不是用来扩展的。你真的想使用
t1(…)
还是打算编写
t1[i][j]=i+j
?使用组合而不是继承是我最近学到的一个艰难的教训。
class int2d : public vector<vector<int>> {
public:
    vector<vector<int>> vec;
    int a;
    int b;

    //vector<int> tmp;
    //vector<vector<int>> vec(b);
    int2d(int a, int b) {

        vector<int> tmp(b);
        vector<vector<int>> vec(a);
        for(int i = 0; i < a; i++) {
            vec.push_back(tmp);
        }
    }

    int2d& operator = (const int2d& X){
        if (this == &X)
            return *this;
        int2d tmp(X.a, X.b);
    }

    int2d& operator = (const int& X){
        vec[a][b] = X;
    }
};