我的班级有一个成员std::string received;,该成员在其构造函数中以空字符串初始化,还有一个函数printReceived,该函数将字符串打印为cout

main()中,创建上述类的实例,并调用printReceived

而不是得到一个空字符串,我得到了完全意外的值(但总是一样):


如果printReceivedstd::cout<<"Received ":<<received<<std::endl;,我得到

Received: eived:作为输出。
如果链接了此文件,则该字符串常量存在于另一个未调用的类的函数中。


那从哪里来?这让我很生气...所有变量都已正确初始化。我以前从未遇到过这个问题,并且我已经用C ++编写了很多程序。

这是所要求的完整的最小示例:

CellularTest.cpp

#include "A.h"

#include <iostream>

int main()
{
    A s;

    s.println("AT+CSQ");

    return 0;
}


丙型肝炎

#include "A.h"

A::A()
: received("")
{
}
void A::println(char* s)
{
    received+=s+'\n';
    treatReceived();
}
void A::treatReceived()
{
    std::cout<<"Received: "<<received<<std::endl;
}




#include <iostream>
#include <string>

class A
{
    public:
        A();
        void println(char* s);
    private:
        std::string received;
        void treatReceived();
};


生成文件

CellularTest: CellularTest.o CellularTest.cpp A.o
    g++ CellularTest.o A.o -o CellularTest

CellularTest.o: CellularTest.cpp

A.o: A.cpp A.h

clean:
    rm *.o
    rm CellularTest


我得到的输出是:

Received: eived:

最佳答案

operator+=的优先级低于operator+。因此,在println中,您正在执行以下操作:

received+=(s+'\n');


就像

received+=(s+10);


这是将指针s递增10个字节,然后将结果char*指向的字符串附加到received,并且字符串文字Recieved:恰好存储在字符串文字AT+CSQ之后。因此内存可能看起来像AT+CSQ\0Received: \0,而将AT+CSQ递增10实际上是e中的Received:。所以你有它。

更改为

received+=s;
received+='\n';


或者

received = received + s + '\n';

关于c++ - std::string获得完全意外的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7313544/

10-12 21:39