【问题标题】:C++, seeing objects in base template class from derived template class [duplicate]C ++,从派生模板类中查看基模板类中的对象[重复]
【发布时间】:2015-01-19 08:56:58
【问题描述】:

当我使用 GCC 4.8.3 编译以下模板化 C++ 代码时

template <typename dtype> class Base {
public:
    dtype base;
    dtype ceiling;
    Base() { };
    virtual ~Base() { };
};

template<typename dtype> class Building : public Base<dtype> {
public:
    dtype wall;
    Building(dtype concrete) { 
        Base<dtype>::base=concrete;
        ceiling=concrete; 
        wall=concrete;
    };

    ~Building() { };
};

int main (int argc, char* argv[]) {

    Building<float>* building=new Building<float>(2.0);

    std::cout << building->base << std::endl;
}

我得到了错误

error: ‘ceiling’ was not declared in this scope
ceiling=concrete; 

看来

Base<dtype>::base=concrete;

有效,但是

ceiling=concrete;

没有。有什么方法可以修改这个模板化代码,以便在派生类构造函数中我可以从模板化基类中引用“天花板”,而不必澄清它来自哪个类?

提前致谢

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    您可以使用this-&gt;ceiling

    【讨论】:

    • 这没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
    • @RiggsFolly 问题(整篇文章中唯一的问题)是:“有什么办法 [...] 我可以直接引用 ceiling [...] 而无需澄清哪个它来自哪个班级?”我的回答是使用this-&gt;ceiling,它有效,是正确的做法,并且准确地回答了作者的问题。我可以继续说这不是写方法(因为Base 应该有构造函数参数并在它自己的构造函数中进行初始化),但我回答了这个问题。
    猜你喜欢
    • 2018-04-22
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 2012-05-20
    相关资源
    最近更新 更多