在C ++ Visual Studio 2019 Cmake项目中使用shared_ptr和unique_ptr制作多态对象向量有困难 [英] having difficulties to make a vector of polymorphic objects using shared_ptr and unique_ptr in C++ Visual studio 2019 Cmake project
问题描述
对于一个练习,我需要构建一个多态对象的向量,由于某些原因,共享和唯一ptr在使用它们时都会产生链接错误2019和1120.我没有选择将旧的内存分配方式与新建"和删除"一起使用,因此我必须使其工作.我尝试了各种不同的语法选项来执行此操作,但仍然没有运气.
For an exercise i need to build a vector of polymorphic objects and for some reason both shared and Unique ptr make linkage errors 2019 and 1120 when i use them. i have no option to use the old way of memory allocation with New and Delete so i have to make it work. i tried various of different syntax options for doing this and still with no luck.
*注意:
我们使用Cmake在Visual Studio中将项目绑定在一起
还将对象分为头文件和cpp文件.
*note:
we use Cmake to bind the project together in visual studio
and also we splitting the objects into header and cpp files.
这是我现在的对象
//This is the abstract base class
#pragma once
#include <string>
class Shape
{
public:
Shape() = default;
virtual ~Shape() = default;
virtual std::string get_name() = 0;
private:
};
这些是派生类:
#pragma once
#include "Shape.h"
class Circle : public Shape
{
public:
Circle();
~Circle();
virtual std::string get_name() override;
private:
std::string m_name;
};
Cpp文件:
#pragma once
#include "Circle.h"
Circle::Circle()
: m_name("Circle")
{
}
Circle::~Circle()
{
}
std::string Circle::get_name() override
{
return m_name;
}
另一个派生类:
#pragma once
#include "Shape.h"
class Rectangle : public Shape
{
public:
Rectangle();
~Rectangle();
virtual std::string get_name() override;
private:
std::string m_name;
};
Cpp文件:
#pragma once
#include "Rectangle.h"
Rectangle::Rectangle()
: m_name ("Rectangle")
{
}
Rectangle::~Rectangle()
{
}
std::string Rectangle::get_name() override
{
return m_name;
}
这是操作程序的类:
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include "Shape.h"
#include "Circle.h"
#include "Rectangle.h"
class Board
{
public:
Board();
~Board();
void run();
void objects_allocation();
private:
std::string m_string;
std::vector<std::shared_ptr<Shape>> m_gates;
};
Cpp文件:
#pragma once
#include "Board.h"
Board::Board()
: m_string(" ")
{
}
Board::~Board()
{
}
void run()
{
while (m_string != "exit")
{
std::cin >> m_string;
}
std::cout << "Goodbye!" << std::endl;
}
void Board::Objects_allocation()
{
m_gates.push_back(std::make_shared <Circle>());
m_gates.push_back(std::make_shared <Rectangle>());
}
这是我的主要功能:
#pragma once
#include "Board.h"
int main()
{
Board board1;
board1.run();
return 0;
}
衷心感谢您能否向我解释这里出了什么问题.
推荐答案
问题出在Cmake文件中.现在一切都按我想要的方式工作.
这篇关于在C ++ Visual Studio 2019 Cmake项目中使用shared_ptr和unique_ptr制作多态对象向量有困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!