简体   繁体   English

带有 const 引用的 C++ Setter 成员函数在运行时导致“读取访问冲突”异常

[英]C++ Setter member function with const reference causes "read access violation" exception at run-time

How do I create a class setter member function that uses const reference as its parameters?如何创建使用 const 引用作为其参数的类 setter 成员函数? I wrote the definition of the setter of how I thought it should be, but upon running it breaks and returns a "read access violation" exception.我写了我认为应该如何设置的 setter 的定义,但是在运行时它会中断并返回“读取访问冲突”异常。

//==== Start of Main.cpp ====
int main()
{
std::string temp="test";
NodeData thingy;

thingy.setname(temp);

return 0;
}
//==== End of Main.cpp ====
//==== Start of NodeData.hpp====
class NodeData
{
public:
void setname(const std::string &newName);

private:
std::string *mpName;
};
//==== End of NodeData.hpp ====
//==== Start of NodeData.cpp====
void NodeData::setname(const std::string &newName)
{
*(this->mpName)=newName;//this here is what causes compiler error I think
//mpName=newName; Doesn't work because "no suitable conversion function from "const std::string" to "std::string *" exists"
}

在此处输入图片说明

The obvious answer is to not use a pointer in your class.显而易见的答案是不要在类中使用指针。

class NodeData
{
public:
    void setname(const std::string &newName);

private:
    std::string mpName;
};

void NodeData::setname(const std::string &newName)
{
    mpName = newName;
}

Newbies often use pointers inappropriately, did you have a good reason for using a pointer in your class?新手经常不恰当地使用指针,你有充分的理由在你的课堂上使用指针吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM