小编Par*_*ita的帖子

如何在模板派生类中调用模板基类的构造函数?

假设我有一个基本模板类Array:

template <class T = Point> class Array{
    protected:
        T* m_data;
        int size;
    public:
        Array();    // constructor
        Array(int n);   // constructor
        Array(const Array<T>& s_data);  //Copy Constructor
        // and so on..
}
Run Code Online (Sandbox Code Playgroud)

它有构造函数和析构函数.我还有一个派生模板类NumericArray:

template <class T = int> 
class NumericArray:public Array<T>{

    public:
        NumericArray();
        NumericArray(int n);
        NumericArray(const NumericArray<T>& s_data);

        ~NumericArray();    //destructor

};
Run Code Online (Sandbox Code Playgroud)

因为我需要初始化基类中的私有成员所以我需要在派生构造函数中调用基础构造函数.但是怎么样?我试过了

template <class T>
NumericArray<T>::NumericArray(int n){
    Array<T>(n);  // it will think I create a Array<T> names n
}

template <class T>
NumericArray<T>::NumericArray(int n):Array(n){
    // No field in NumericalArray called Array …
Run Code Online (Sandbox Code Playgroud)

c++ templates

8
推荐指数
1
解决办法
1万
查看次数

无法从函数返回临时对象

在头文件中:

class Point{
    public:
        Point();    // constructor
        Point(double x, double y);  // constructor
        Point(Point& A);    //Copy Constructor
        ~Point();   // destructor

        // below are the operator declarations. 
        Point operator - () const; // Negate the coordinates.

    private:
        double xCord;
        double yCord;

};
Run Code Online (Sandbox Code Playgroud)

在Cpp实现文件中,相关的构造函数:

Point::Point(double x, double y){   // constructor
    X(x);// void X(double x) is a function to set the xCord 
    Y(y);// so is Y(y)

}

Point Point::operator-() const{ // Negate the coordinates.
    Point temp(-xCord,-yCord);
    return temp;
    // return Point(-xCord,-yCord); // cannot …
Run Code Online (Sandbox Code Playgroud)

c++

1
推荐指数
1
解决办法
83
查看次数

标签 统计

c++ ×2

templates ×1