不能使用默认赋值运算符

不能使用默认赋值运算符

本文介绍了“非静态引用成员,不能使用默认赋值运算符"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译代码时出现此错误:非静态参考成员"Timestep&Timestep :: previousTimestep",不能使用默认的赋值运算符

I get this error when i try to compile my code:non-static reference member ‘Timestep& Timestep::previousTimestep’, can’t use default assignment operator

我创建了一个 Problem 问题,该问题创建了一个 Timestep 引用,此 Timestep 的引用应存储在向量 solution .此外,我想存储对以前的 Timestep 的引用-对于第一个Timestep,这将是对自身的引用...

I create one Problem which creates a Timestep a reference to the this Timestepshould be stored in the vector solution. Besides i want to store a reference to a previous Timestep - and for the first Timestep that would be a reference to itself...

我了解到,如果我在类中具有 const 成员,则需要定义一个自己的运算符,而我尝试将其设置为相等.但是,从代码中删除了所有 const 元素,但仍然无法正常工作.有什么建议么?非常感谢.

I read that i need to define an own operator if i have const members in a class what i try to set equal. However, removed all const elements form the code and it still don't work. Any suggestions? Thanks a lot.

class Problem {
public:
    void initialTimestep(arma::vec ic);
private:
    std::vector<Timestep> solution;
};

void Problem::initialTimestep(vec ic){
    Timestep myFirstTimestep(starttime, ic, nodes);
    solution.push_back(myFirstTimestep);
}



class Timestep {
public:
    Timestep(double starttime, arma::vec initialCondition, arma::vec nodelist);
private:
    Timestep& previousTimestep; //const
};

Timestep::Timestep(double starttime, vec initialCondition, vec nodelist)
: previousTimestep(*this)
    {
    //do stuff
}


int main() {
    int k = 3; //subdomains
    vec v = linspace(0., 1., k+1); //node spacing
    vec ic= ones<vec>(k+1); //initialconditions
    Problem myProblem(v, ic, 0., 1., 0.1);
    return 0;
}

推荐答案

没有为您的类 Timestep 创建默认赋值运算符,因为它包含一个引用(以后无法设置.它基本上是一个指向非常量数据的常量指针).尽管 solution.push_back(myFirstTimestep)需要分配(或与c ++ 11一起移动),所以您将必须定义自己的分配(或移动)运算符(当然,您将无法指定该赋值(或移动)运算符)除非将 Timestep& amp; TimeTime 更改为 Timestep * previousTimestep ,否则默认分配也将起作用).

No default assignment operator was created for your class Timestep because it contains a reference (which cannot be set later. it basically is a constant pointer to non-const data).solution.push_back(myFirstTimestep) requires the asignment though (or move with c++11) so you will have to define your own assignment (or move) operator (which of course you will not be able to do unless you change Timestep& previousTimestep to Timestep *previousTimestep in which case the default assignment will work as well).

这篇关于“非静态引用成员,不能使用默认赋值运算符"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 18:17