通过向构造函数其他对象引用页面来创建对象
Create an object by paasing to the constructor other object reference
我在include.hpp中创建了两个C++类:
#include <string>
#include <map>
#include <iostream>
#include <sstream>
#include<vector>
using namespace std;
class A {
public:
vector<char> v;
A(){};
A(A &other) {
v = other.v;
}
A(string s) {
v.assign(s.begin(), s.end());
}
A& operator << (std::string s) {
v.insert(v.end(), s.begin(), s.end());
return(*this);
};
};
class B {
protected:
A a;
public:
template<typename T>
B(T &t): a(t) {}
};
我现在需要通过在其构造函数中输入一个 A 对象来创建实例。 此外,A 对象必须是另一个函数的返回值,该函数使用运算符 <<创建返回的 A 实例
我正在尝试使用以下主要方法:
#include<iostream>
#include "include.hpp"
using namespace std;
A& createstrbyappend() {
A a;
a << "aa";
return a;
}
int main() {
A aa;
aa << "kkk";
cout << "create b1 object " << endl;
B* b1 = new B(aa);
cout << "create b2 object " << endl;
B* b2 = new B(createstrbyappend());
cout << "End program " << endl;
}
但是我在这个主要方面遇到了分段错误,我得到输出:
create b1 object
create b2 object
Segmentation fault (core dumped)
B1 创建成功,但通过函数 createstrbyappend 创建的 B2 会出现分段错误。
有没有建议我如何解决这个问题?
编辑:添加编译器版本
我正在 ubuntu 下使用 g++ 命令进行编译。 我的 G++ 版本如下:
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
您正在通过引用从createstrbyappend
返回函数本地对象。您应该返回一份副本:
A createstrbyappend() {
//...
}
这要求你把参数也按值B
构造函数:
template<typename T>
B(T t): a(std::move(t)) {}
现在,您需要将参数带到A
的复制构造函数中const&
:
A(A const &other) {
v = other.v;
}
这是一个工作演示。
相关文章:
- 为什么当我们有常量引用时创建临时对象?
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 如何从绝对地址的 C 样式指针创建对C++对象的引用
- 为什么在取消引用/释放动态创建的对象后,它仍然在 c++ 中被引用?
- 创建对满足特定谓词的对象的引用元组
- 创建返回对象引用的成员函数的最简单方法
- C++问题返回通过引用本地创建的对象
- 如何返回对在方法中创建的对象的引用
- 如何实现一个创建新对象并返回对它的引用的C++方法
- 以这种方式返回对新创建的对象的引用,这是一种安全的做法
- 通过引用捕获异常时未创建临时对象
- C++:初始化在初始化列表中创建的对象的引用成员
- 保留对象和对在函数中创建的对象的引用
- 获取 Java VM 引用,从C++和并发创建 Java 对象
- 递增由向 boost::p ython 公开的构造函数创建的对象的引用计数
- 您能否从抽象引用创建具体对象的副本
- 是为添加常量而重新创建的对象/引用/指针
- 在引用初始化期间如何创建临时对象
- 如何创建一个静态方法来返回对该类对象的引用
- 从unique_ptr返回引用有时会创建其对象的副本吗