gpt4 book ai didi

C++构造函数看不到成员对象的成员

转载 作者:太空宇宙 更新时间:2023-11-04 15:41:01 24 4
gpt4 key购买 nike

我遇到了一个奇怪的情况:我有一个包含一些字符串成员的对象,我用它来初始化其他一些成员,如下所示:

class A
{
private:
B b;
C c1;
C c2;

public:
A(const string& str) : b(str), c1(b.foo1()), c2(b.foo2()) {}

// ...
};

class B
{
public:
B(const string& str)
{
// ...
}
string& foo1()
{
string s1;
// initialization
return s1;
}
string& foo2()
{
string s2;
// initialization
return s2;
}
};
class C
{
private:
string s;
public:
C(const string& str) : s(str) {}
};

当我调用 A 的构造函数时:

string str = "some string here";
A(str);

我收到以下错误:

terminate called after throwing an instance of 'std::length_error'
what(): basic_string::replace

问题出在这里:

A(const string& str) // str == "some string here"
: b(str), // enters the B(str), str == "some string here"
c1(b.foo1()), // enters the C(str), str the string that I want
c2(b.foo2()) // enters the C(str), but str is not visible
  • 我不知道发生了什么。
  • 成员 A::b 是否超出范围?
  • 无论我使用foo1()还是foo2()来初始化c2,问题都是一样的

你建议我怎么做?

最佳答案

您正在返回对 foo1foo2(分别为 s1s2)中的局部变量的引用这是不允许的,使用引用将调用未定义的行为。

关于C++构造函数看不到成员对象的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23082631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com