先看代码(不想看代码可以直接看代码后的问题描述)

//header.h
#ifndef _HEADER_H
#define _HEADER_H
#define defaultSize 128
#include<iostream>
#include<string.h>
using namespace std;
class myString
{
private:
char *ch;
int curLength;
int maxSize;
public:
myString(int sz=defaultSize);
myString(const char *init);
myString(const myString& ob);
~myString(){delete []ch;}
void print();
int Length()const;
myString operator()(int pos, int len);
myString& operator = (myString& ob);
};
myString& myString::operator = (myString& ob)
{
if(&ob!=this)
{
delete[]ch; this->ch = new char[ob.maxSize];
this->maxSize = ob.curLength;
strcpy(this->ch, ob.ch);
this->curLength = ob.curLength;
}
else
{
cerr<<"String copy error\n";
}
return *this;
} myString myString::operator()(int pos, int len)
{
myString temp;
if(pos<0 || len<=0 || pos+len-1>=this->maxSize)
{
temp.curLength = 0;
temp.ch[0] = '\0';
}
else
{
if(pos+len-1 >= this->curLength)
len = this->curLength-pos;
temp.curLength = len;
for(int i=0,j=pos; i<len; ++i,++j)
temp.ch[i] = this->ch[j];
temp.ch[len] = '\0';
}
return temp;
} int myString::Length()const
{
return this->curLength;
} void myString::print()
{
cout<<this->ch<<endl;
} myString::myString(int sz)
{
this->maxSize = sz;
this->ch = new char[this->maxSize+1];
if(this->ch == NULL)
{
cerr<<"Allocation ERROR\n";
exit(1);
}
this->curLength = 0;
ch[0] = '\0';
} myString::myString(const char *init)
{
int len = strlen(init);
this->maxSize = (len > defaultSize) ? len : defaultSize;
this->ch = new char[this->maxSize+1];
if(this->ch == NULL)
{
cerr<<"Application Memory ERROR\n";
exit(1);
} this->curLength = len;
strcpy(this->ch, init); } myString::myString(const myString& ob)
{
this->maxSize = ob.maxSize;
this->ch = new char[this->maxSize+1];
if(this->ch == NULL)
{
cerr<<"Application Memory ERROR\n";
exit(1);
}
this->curLength = ob.curLength;
strcpy(this->ch, ob.ch); } #endif
//main.cpp
#include"header.h" int main()
{
myString st(10), st1("ABCDEFG");
myString st2(st1);
st.print(), st1.print(), st2.print();
st = st1(0, 4);//???
st.print();
return 0;
}

这是一个字符串类,问题出现在了两个符号重载,()和=

()重载是想对字符串对象做一个切片,返回一个临时对象,=重载就不用说了,就是赋值。

问题就出现在总是无法将这个切片后的临时对象赋值给等号前的对象,编译后如下:

在网上一番查找后找到一个类似问题

https://blog.csdn.net/u011068702/article/details/64443949

也就是说,在st1(0,4)时存在了一个临时变量,当把这个临时变量传给st时,由于在=重载函数声明中,参数为myString&,而并不是常量引用。

这个错误是C++编译器的一个关于语义的限制。

如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,所以,一般说来,修改一个临时变量是毫无意义的,据此,c++编译器加入了临时变量不能作为非const引用的这个语义限制。

了解这个语义以后就简单了,只需给=重载参数加上const常量限制符。

(类中=重载函数声明也别忘了要加上const)

加上以后程序的运行结果

可以,很正确。

总结:

c++中临时变量不能作为非const的引用参数

2019/12/14更新

最近看到一个类似问题,即C++11

int i=0;
++++i;//这样是可以的
i++++;//这样就是错误的

我们知道前++就是直接对对象自增后返回对象,而后++会先返回记录当前值,在自增,最后返回一个无名的临时对象,那么 i++++就是让第一个后++返回的无名临时对象再自增,这样对C++是无意义的,所以这样就无法编译通过。//ps.这就是常说的  举一隅以三隅反  吧

C++之error: cannot bind non-const lvalue reference of type ‘myString&’ to an rvalue of type ‘myString’的更多相关文章

  1. C++ non-const lvalue reference cannot bind to a temporary

    1. 问题代码 #include <iostream> #include <vector> //注意begin和end形参都声明为引用 bool find_int(std::v ...

  2. caffe: fuck compile error again : error: a value of type "const float *" cannot be used to initialize an entity of type "float *"

    wangxiao@wangxiao-GTX980:~/Downloads/caffe-master$ make -j8find: `wangxiao/bvlc_alexnet/spl': No suc ...

  3. ERROR: transport error 202: bind failed: Address already in use

    早上上班,同事反应服务上不去,后台看了一下,发现tomcat挂掉了,重新启动tomcat时报错. ERROR: transport error 202: bind failed: Address al ...

  4. error: C2664: “zajiao::zajiao(const zajiao &)”: 无法将参数 1 从“const char [12]”转换为“char *”

    原本打算在QT用一个字符串"ABCDEF12345"作为类zajiao的构造函数的参数,用来创建类zajiao的对象zajiao1. zajiao zajiao1("AB ...

  5. ERROR C3848:具有类型"const XXX" 的表达式会丢失一些 const-volatile 限定符以调用"YYY" with"ZZZ"

    今天看书,Thinking in c++ volume 2 "Adaptable function objects" 里面作者说: Suppose, for example, th ...

  6. Tomcat启动报错ERROR:transport error 202:bind failed:Address already

    昨天在服务器上拷贝了一个tomcat项目,修改了server.xml之后启动居然报错ERROR:transport error 202:bind failed:Address already,应该是远 ...

  7. PHP Fatal error: Cannot pass parameter 2 by reference

    PHP Fatal error:  Cannot pass parameter 2 by reference in 这个错误的意思是:不能按引用传递第2个参数 我的理解是: 方法的第2个参数 需要传递 ...

  8. fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'

    xxxxxx.lib(xxxxxx.obj) : fatal error LNK1112: module machine type 'X86' conflicts with target machin ...

  9. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'catchFromPBomService': Cannot create inner bean '(inner bean)#302efb82' of type [com.thinkgem.jeesite.modules.fd

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'catchFromPBo ...

随机推荐

  1. IELTS6 2020.7 Translation

    原文 <三国演义>(The Romance of the ThreeKingdoms)是中国一部著名的历史小说,写于十四世纪.这部文学作品以三国时期的历史为背景,描写了从公元二世纪下半叶到 ...

  2. 从ACID到CAP及BASE

    从ACID到CAP及BASE ACID 说到事务,肯定想到事务的ACID特性,即原子性(Atomicity).一致性(Consistency).隔离性(Isolation).持久性(Durabilit ...

  3. Linux内核 fork 源码分析

    内核版本:linux-4.4.18 源码位置:这里 fork相关的代码最终执行的函数为_do_fork(),下面按照顺序分析下_do_fork(): 首先判断是否需要trace(跟踪)这个进程,这一步 ...

  4. Window黑客编程之资源释放技术

    前言 今天说一下写病毒木马会广泛使用的一种技术--资源释放技术.为什么我们在写木马时会使用到资源释放技术呢?这是因为它可以使我们写的程序变得简洁.如果程序需要额外加载一些DLL文件或者文本文件,我们可 ...

  5. Centos6.8 yum报错及修复YumRepo Error: All mirror URLs are not using ftp, http[s] or file. Eg. Invalid

    问题 使用yum安装软件时报错 YumRepo Error: All mirror URLs are not using ftp, http[s] or file. Eg. Invalid relea ...

  6. Python打包成exe,文件太大问题解决办法

    Python打包成exe,文件太大问题解决办法 原因 解决办法 具体步骤 情况一:初次打包 情况二:再次打包 原因 由于使用pyinstaller打包.py文件时,会把很多已安装的无关库同时打包进去, ...

  7. c++学习笔记4(函数重载)

    一个或多个函数,名字相似,然而参数个数或类型不同,这个叫做函数重载 优点:可以使函数的命名变得简单

  8. AnnotationConfigApplicationContext(1)之初始化Scanner和Reader

    AnnotationConfigApplicationContext(1)初始化Scanner和Reader 我们以AnnotationConfigApplicationContext为起点来探究Sp ...

  9. python实现图片色素的数值运算(加减乘除)和逻辑运算(与或非异或)

    目录: (一)数值运算(加减乘除) (二)逻辑运算(与或非异或) 正文: (一)数值运算(加减乘除) opencv自带图片色素的处理函数------相加:add()   相减:subtract()  ...

  10. 容器安全产品Aqua调研

    前言 近年来,随着云计算的发展,企业数字化的进程不断加快,业务纷纷开始上云,云原生的概念最近两年也是十分火热,在新业务场景下也随之产生了新的安全问题,如k8s安全.devsecops.微服务安全.Se ...